Use Win32 API through dllimport in C #

Source: Internet
Author: User

The. NET Framework Program can access the local code library through the static DLL entry point. The dllimport attribute is used to specify the DLL location that contains the implementation of an external method.

The dllimport attribute is defined as follows:

Namespace system. runtime. interopservices
{
[Attributeusage (attributetargets. Method)]
Public class dllimportattribute: system. Attribute
{
Public dllimportattribute (string dllname ){...}
Public callingconvention;
Public charset;
Public String entrypoint;
Public bool exactspelling;
Public bool preservesig;
Public bool setlasterror;
Public String Value {get {...}}
}
}

Note:

1. dllimport can only be placed on method declaration.
2. dllimport has a single positioning parameter: Specify the dllname parameter that contains the DLL name of the imported method.
3. dllimport has five naming parameters:
A. The callingconvention parameter indicates the call convention of the entry point. If no callingconvention is specified, use the default value callingconvention. winapi.
B. The charset parameter indicates the character set used in the entry point. If charset is not specified, the default value charset. Auto is used.
C. The entrypoint parameter specifies the name of the DLL entry point. If entrypoint is not specified, the method name is used.
D. The exactspelling parameter indicates whether the entrypoint must exactly match the spelling of the indicated entry point. If exactspelling is not specified, use the default value false.
E. The preservesig parameter indicates whether the method signature should be retained or converted. When the signature is converted, it is converted to a signature with an additional output parameter named retval that has the hresult return value and the return value. If preservesig is not specified, the default value true is used.
The F and setlasterror parameters indicate whether the method retains Win32 "previous error ". If setlasterror is not specified, the default value false is used.

4. It is a one-time attribute class.
5. In addition, the method modified with the dllimport attribute must have an extern modifier.

The following is an example of C # calling the Win32 MessageBox function:

Using system;
Using system. runtime. interopservices;
Class mainapp
{

// Use dllimport to reference the user32.dll class. MessageBox comes from the user32.dll class
[Dllimport ("user32.dll", entrypoint = "MessageBox")]
Public static extern int MessageBox (INT hwnd, string strmessage, string strcaption, uint uitype );
Public static void main ()
{
MessageBox (0, "Hello, this is pinvoke! ",". Net ", 0 );
}
}

Object-Oriented Programming Languages almost all use the concept of abstract classes, which provide greater flexibility for implementing abstract things. C # is no exception. C # deepens the application of abstract classes by overwriting virtual interfaces. For more information, see the next section-overwrite virtual interfaces.

Here we are talking about the issue of C # Calling standard dynamic libraries. I have mentioned in my previous files that C # uses the same principle to call WIN32API. here I will explain in detail how to use C to write a standard dynamic library and then let C # Call it. (This article is suitable for beginners. There is no redundant code in the middle. It is concise and clear)
Software environment: vc6.0 (of course other versions of vc5 can also be used)
1. Create a standard dynamic library
_ Declspec (dllexport) int _ cdecl add (INT, INT); // This statement declares that the dynamic library outputs a prototype of a function that is available for external calls.
Int add (int A, int B) {// implement this function
Return A + B;
}
The preceding three lines of code declare an add method. The input parameter is the sum of the two int parameters and is saved as mylib. C.
Then execute the compilation command.
H:/xschool/C #-school/howto> Cl/LD mylib. c
Microsoft (r) 32-bit C/C ++ Optimizing Compiler version 12.00.8168 for 80x86
Copyright (c) Microsoft Corp 1984-1998. All rights reserved.

Mylib. c
Microsoft (r) incremental linker version 6.00.8447
Copyright (c) Microsoft Corp 1992-1998. All rights reserved.

/Out: mylib. dll
/DLL
/Implib: mylib. Lib
Mylib. OBJ
Creating library mylib. lib and object mylib. Exp

If the above output is confirmed, the dynamic library is successfully generated.

2. Write a C-sharp program to call the dynamic library
Using system;
Using system. runtime. interopservices; // This is the package to be introduced when you use dllimport.

Public class invokedll {
[Dllimport ("mylib. dll", charset = charset. Auto)]
Static extern int add (int A, int B); // declare an external standard dynamic library, which is the same as WIN32API.

Public static void main (){
Console. writeline (add (10, 30 ));
}
}
Save as the invokedll. CS file, and put it in the same directory as mylib. DLL to compile the file.
H:/xschool/C #-school/howto> CSC invokedll. CS
Invokedll.exe will be generated to execute this file.
The above is the whole process of C-Sharp calling the standard dynamic library. I thought it was very simple and never wanted to write it. Today, when a friend asked me about it, I wrote it by the way.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.