C # Call C ++ DLL through P/invoke

Source: Internet
Author: User

From: http://hacker.cnblogs.com/archive/2004/08/12/32563.aspx

1. What does pinvoke mean? Platform invocation services

2. What should I do? Import external functions? What is an external function is a function not hosted by. net.

3. How to use it? Let's look at the example below. [Dllimport (dllname)] is used for implementation. However, you must first include system. runtiime. interopservices using. But you can do it without using. You have to enter the full name.

[Dllimport ("user32.dll")]
Static extern int messageboxa (INT hwnd,

String MSG,

String caption,

Int type );

Private void button#click (Object sender, system. eventargs E)

{

Messageboxa (0, "MSG: Hello", "caption: Hello", 0 );

}

4. What if I already have a function named messageboxa in my program? In this case, entrypoint can be used for help. In the following example, you define your function as mymsg.

[Dllimport ("user32.dll", entrypoint = "messageboxa")]

Static extern int mymsg (INT hwnd,

String MSG,

String caption,

Int type );

Private void button#click (Object sender, system. eventargs E)

{

Mymsg (0, "MSG: Hello", "caption: Hello", 0 );

}

5. How to Use charset? * *** A is ANSI encoded, and *** W is unicode encoded. How to Use charset depends on your function call. Unicode will be used later than 2 K. The first 9x is ANSI encoded, but this is the default. It is not counted if Microsoft supports Unicode for 9x pudding.

The API has two versions: A (asni) version and w (UNICODE) version. A use ANSI to block strings when calling, generally on Win95/98. In version W, Unicode is used for sending messages, on NT, 2 K, and XP.

When. Net interacts with Win32, charset. ANSI is used by default for transmission.

When the dllimportattribute. exactspelling field is set to true (it is the default value in Visual Basic. Net), only the name you specified is searched for Platform calls. For example, if MessageBox is specified, the platform call will search for MessageBox. If it cannot find the exact same spelling, it will fail.

When the exactspelling field is false (it is the default value in C ++ managed extension and C #), the platform call first searches for unprocessed aliases.
(MessageBox). If no unprocessed alias is found, the processed name (messageboxa) will be searched ). Note that ANSI names match
Unicode name matching behaviors are different.

// Charset. ANSI will call messageboxa

// Charset. Unicode will call messageboxw

 

[Dllimport ("user32.dll", entrypoint = "MessageBox", charset = charset. ANSI)]

Static extern int mymsg (INT hwnd,

String MSG,

String caption,

Int type );

Private void button#click (Object sender, system. eventargs E)

{

Mymsg (0, "MSG: Hello", "caption: Hello", 0 );

}

6. How do I implement the callback function in the DLL? Let's look at the example below:

Delegate bool callbackdef (INT hwnd, int lparm );

 

[Dllimport ("user32.dll")]

Static extern int getwindowtext (INT hwnd,

Stringbuilder text,

Int count );

[Dllimport ("user32.dll")]

Static extern int enumwindows (callbackdef callback, int lparam );

 

Static bool printwindow (INT hwnd, int lparm)

{

Stringbuilder text = new stringbuilder (255 );

Getwindows text (hwnd, text, 255 );

Console. writeline (text. tostring ());

 

Return true;

}

 

Private void button#click (Object sender, system. eventargs E)

{

Callbackdef callback = new callbackdef (printwindow );

Enumwindows (callback, 0 );

}

7. How can I use marshalas? When can I use it?
When MessageBox transmits a string to the DLL, the C # compiler knows that win32lpstr is equivalent to a C # string. However, if you want to override the default. Net behavior, you need to override allas.

[Dllimport ("user32.dll", charset = charset. Unicode)]

Static extern int MessageBox (INT hwnd,

[Financialas (unmanagedtype. lpwstr)]

String MSG,

[Financialas (unmanagedtype. lpwstr)]

String caption,

Int type );

8. How do I know that the function to be called is in that DLL?
I won't know more about this problem than you do. Special functions should be in your special DLL. The common DLL in Win32 is user32.dll, kernel32.dll, and gdi32.dll. You can use dumpbin-Exports kernel32.dll to view all the API functions of this DLL.

9. What should I do if I transfer struct to each other? I mean, passing a complex struct?
To pass a structure, the structlayoutattribute attribute is used. For example:

Ptinrect has the following unmanaged signatures:
Bool ptinrect (const rect * LPRC, point pt );
Note that because the function needs to point to the rect type pointer, The rect structure must be passed through reference.

Using system. runtime. interopservices;


[Structlayout (layoutkind. Sequential)]

Public struct point

{

Public int X;

Public int y;

}

 

[Structlayout (layoutkind. explicit)]

Public struct rect

{

[Fieldoffset (0)] public int left;

[Fieldoffset (4)] public int top;

[Fieldoffset (8)] public int right;

[Fieldoffset (12)] public int bottom;

}

 

Class WIN32API

{

[Dllimport ("user32.dll")]

Public static extern bool ptinrect (ref rect R, point P );

}

10. Where can I learn more details about a good tutorial?
Google is mostly used. There are also some good tutorials in msdn: (vs.net 2003)

11. At last, this eldest brother, you said a lot. I want to ask the most critical question for me. I have read your things and it seems like nothing. What should I do?

I have prepared a site for you. Here is the add-in tools for Visual Studio. NET of pinvoke, which is available in almost all Win32 APIs. After the installation, you do not need to write it yourself.

Platform call data type
Lists managed data types and their corresponding unmanaged data types.
Mail string
Describes how to pass a string through a value, by reference, in a structure, in a class, or in an array.
Mail class, structure, and Union
Describes how to pass classes through values, how to pass various structures, and how to pass the Union with values and mixed types.
Mail type array
Describes how to pass a multi-dimensional integer array by value and how to pass a one-dimensional array by reference.
Other mail handling examples
Describes the garbage collection and thread processing that affect InterOP mail handling.
Http://www.pinvoke.net

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.