Platform call: C # use an unmanaged DLL Function

Source: Internet
Author: User

I'm studying WorldWind'sSource codeThe underlying layerCodeA large number of external DLL calls, including the DLL of different platforms. That is, the unmanaged DLL function is called in the hosting Language C. In the past, I also encountered such a situation, but I did not learn and understand it deeply. Now, I have learned a few parts to make up for this deficiency!

InterOP refers to the interoperability between hosted and unmanaged code.

Extern (C # reference ): Http://msdn.microsoft.com/zh-cn/library/e59b22c5 (vs.80). aspx

ExternModifierThe method used to declare an external implementation.ExternThe common usage of modifiers isDllimportAttribute used together;In this case, the method must also be declaredStatic, As shown in the following example:

[Dllimport ("avifil32.dll")]
Private Static extern void avifileinit ();

It is incorrect to use the abstract and extern modifiers together to modify the same member.The use of the extern modifier means that the method is implemented externally in the C # code, while the use of the abstract modifier means that the method implementation is not provided in the class.

Example:

In this example,ProgramReceives a string from the user and displays the string in the message box. Program usageUser32.dllLibrary importedMessageBoxMethod.

Using system;
Using system. runtime. interopservices;
Class mainclass
{
[Dllimport ("user32.dll")]
Public static extern int MessageBox (int h, string M, string C, int type );

Static int main ()
{
String mystring;
Console. Write ("Enter your message :");
Mystring = console. Readline ();
Return MessageBox (0, mystring, "My message box", 0 );
}
}Dllimportattribute class:Http://msdn.microsoft.com/zh-cn/library/system.runtime.interopservices.dllimportattribute (vs.80). aspx

Indicates that the attribute method is exposed by an unmanaged dynamic link library (DLL) as a static entry point.. Methods for modifying the dllimport attributeMust have a static extern modifier.

Namespace:System. runtime. interopservices

DllimportattributeAttribute provides the information necessary to call a function exported from an unmanaged DLL. As the minimum requirement, the name of the DLL containing the entry point must be provided. This attribute can be directly applied to the C # Or C ++ method definition;

Note:JScript does not support this attribute. You can use the C # or visual basic packaging class to access the unmanaged API method from a JScript program.

Example

The following code example demonstrates how to useDllimportattributeProperty import Win32MessageBoxFunction. The sample code then calls the import method.

 Using System; Using System. runtime. interopservices; Class Example { // Use dllimport to import the Win32 MessageBox function. [Dllimport ( "User32.dll" , Charset = charset. Auto)]Public   Static Extern Int MessageBox (intptr hwnd, string text, string caption, uint type ); Static   Void Main (){ // Call the MessageBox function using platform invoke. MessageBox ( New Intptr (0 ), "Hello world! " , "Hello dialog" , 0 );}}

Using Unmanaged DLL Functions: http://msdn.microsoft.com/zh-cn/library/26thfadc (vs.80). aspx

Using the platform to call such a service, managed code can call the unmanaged functions implemented in the dynamic link library (DLL) (such as the DLL in Win32 API. This service searches for and calls the exported function, and then sends its parameters (integers, strings, arrays, structures, etc.) across the mutual border as needed ).

Use exported DLL Functions

  1. Identifies the function in the DLL.

    At the minimum, you must specify the name of the function and the name of the DLL that contains the function.

  2. Create a class to hold DLL functions.

    You can use an existing class to create a separate class for each unmanaged function, or create a class that contains a group of related unmanaged functions.

  3. Create the original type in the managed code.

    [Visual Basic]FunctionAndLibKeywordDeclareStatement. In some rare cases, you can useShared FunctionKeywordDllimportattribute. These situations are described later in this section.

    [C #] usageDllimportattributeIdentifies the DLL and function. UseStaticAndExternModifier marking method.

    [C ++] usageDllimportattributeIdentifies the DLL and function. UseExtern "C"Mark the packaging method or function.

  4. Call the DLL function.

    Call methods on the Managed class just like any other managed method. The transfer structure and implementation of callback functions are special cases.

Platform calls allow you to call Win32 APIs and other DLL functions to control a large part of the operating system. In addition to Win32 APIs, there are many other APIs and DLL that can be called through the platform.

The following table describes the commonly used DLL in Win32 APIs.

DLL Description

Gdi32.dll

Graphical device interface (GDI) functions used for device output, such as functions used for drawing and font management.

Kernel32.dll

Low-level operating system functions for memory management and resource processing.

User32.dll

Windows management functions for message processing, timers, menus, and communication.

 

Platform call example: http://msdn.microsoft.com/zh-cn/library/42b9ea93 (vs.80). aspx

The following example shows how to define and callMessageBoxFunction, and pass a simple string as a parameter. In these examples, the dllimportattribute. charset field is setAutoSo that the target platform can determine the character width and string sending.

C #

Using System. runtime. interopservices; Public   Class Win32 {[dllimport ( "User32.dll"  ,  Charset = charset.  UT O)] Public   Static  EXT  Ern int PTR MessageBox ( Int Hwnd, string text, string caption, uint type );}Public   Class Helloworld { Public   Static   Void Main () {win32.messagebox (0, "Hello World" , "Platform invoke sample" , 0 );}}

C ++
 Using   Namespace System: runtime: interopservices; typedef Void * Hwnd; [dllimport ("USER32" , Charset = charset: auto)] extern "C" Intptr MessageBox (hwnd, string * ptext, string * pcaption, unsigned Int Utype ); Void Main ( Void ) {String * ptext = L "Hello world! " ; String * pcaption = L "Platform invoke sample" ; MessageBox (0, ptext, pcaption, 0 );}


 

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.