C # dynamic calling of DLL functions written in C ++

Source: Internet
Author: User

[C # dynamic calling of DLL functions written in C ++]

 

Dynamic DLL loading requires the use of Windows API functions: loadlibrary, getprocaddress, and freelibrary. We can use these three functions in C # using dllimport.

[Dllimport ("Kernel32")]
Public static extern int getprocaddress (INT handle, string funcname );

[Dllimport ("Kernel32")]
Public static extern int loadlibrary (string funcname );

[Dllimport ("Kernel32")]
Public static extern int freelibrary (INT handle );

When we dynamically call functions in DLL in C ++, the general method is:
Assume that the dll contains an export function. The function prototype is as follows:
Bool _ stdcall Foo (Object & object, lpvoid lpreserved );

1. First define the corresponding function pointer:
Typedef bool (_ stdcall * pfoo) (Object & object, lpvoid lpreserved );

2. Call loadlibrary to load dll:
Hinstance hinst =: loadlibraryw (dllfilename );

3. Call the getprocaddress function to obtain the address of the function to be called:
Pfoo Foo = (pfoo) getprocaddress (hinst, "foo ");
If (FOO = NULL)
{
Freelibrary (hinst );
Return false;
}

4. Call the foo function:
Bool Bret = Foo (object, (lpvoid) null );

5. Release the DLL after use:
Freelibrary (hinst );

So what should I do in C? The method is basically the same. We use a delegate to replace the function pointer of C ++, and use the new function getdelegateforfunctionpointer of. NET Framework 2.0 to get an instance of delegation:

The following encapsulates a class, through which we can dynamically call functions in DLL in C:

Public class dllwrapper
{
/// <Summary>
/// API loadlibrary
/// </Summary>
[Dllimport ("Kernel32")]
Public static extern int loadlibrary (string funcname );

/// <Summary>
/// API getprocaddress
/// </Summary>
[Dllimport ("Kernel32")]
Public static extern int getprocaddress (INT handle, string funcname );

/// <Summary>
/// API freelibrary
/// </Summary>
[Dllimport ("Kernel32")]
Public static extern int freelibrary (INT handle );

/// <Summary>
/// Use an unmanaged function name to convert to the corresponding delegate, by jingzhongrong
/// </Summary>
/// <Param name = "dllmodule"> DLL handle obtained through loadlibrary </param>
/// <Param name = "functionname"> unmanaged function name </param>
/// <Param name = "T"> delegate type </param>
/// <Returns> delegate instance, which can be forcibly converted to an appropriate delegate type </returns>
Public static delegate getfunctionaddress (INT dllmodule, string functionname, type T)
{
Int address = getprocaddress (dllmodule, functionname );
If (address = 0)
Return NULL;
Else
Return marshal. getdelegateforfunctionpointer (New intptr (address), t );
}

/// <Summary>
/// Convert the intptr instance indicating the function address to the corresponding delegate, by jingzhongrong
/// </Summary>
Public static delegate getdelegatefromintptr (intptr address, type T)
{
If (address = intptr. Zero)
Return NULL;
Else
Return marshal. getdelegateforfunctionpointer (address, t );
}

/// <Summary>
/// Convert the int representing the function address to the corresponding delegate, by jingzhongrong
/// </Summary>
Public static delegate getdelegatefromintptr (INT address, type T)
{
If (address = 0)
Return NULL;
Else
Return marshal. getdelegateforfunctionpointer (New intptr (address), t );
}
}

Through this class, we call the DLL as follows:

1. Declare the relevant delegate (correct declaration is very important; otherwise, the call cannot be successful, which will be detailed later ).

2. Load dll:
Int hmodule = dllwrapper. loadlibrary (dllfilepath );
If (hmodule = 0)
Return false;

3. obtain the corresponding delegated instance:
Foo = (FOO) dllwrapper. getfunctionaddress (hmodule, "foo", typeof (FOO ));
If (FOO = NULL)
{
Dllwrapper. freelibrary (hmodule );
Return false;
}

4. Call a function:
Foo (...);

5... Net does not automatically release the Dynamically Loaded DLL. Therefore, we should release the DLL after using it:
Dllwrapper. freelibrary (hmodule );

Next, we will discuss how the delegation should be declared. in the actual operation process, I found that the declaration of the function prototype in DLL in C # by using the dllimport method and the dynamic call method is somewhat different. Next I will introduce the declaration of delegation in the dynamic call:

1. The first thing to note is the correspondence between types in C ++ and types in C #. For example, long in C ++ should correspond to int32 in C # Instead of long, otherwise, an error occurs in the call result.

2. The structure Declaration uses structlayout to set the corresponding layout of the structure. For details, see msdn:

Use layoutkind to specify the layout sequence of members in the structure. Generally, you can use sequential:
[Structlayout (layoutkind. Sequential)]
Struct structversioninfo
{
Public int majorversion;
Public int minorversion;
}
In addition, if the internal type is used separately without strings, structures, and classes, you can declare the structure in C # As class:
[Structlayout (layoutkind. Sequential)]
Class structversioninfo
{
Public int majorversion;
Public int minorversion;
}

Corresponds to the statement in C ++:
Typedef struct _ version_info
{
Int majorversion;
Int minorversion;
} Version_info, * pversion_info;

If strings are used in the structure, it is best to specify the corresponding character set:
[Structlayout (layoutkind. Sequential, charset = charset. Unicode)]

Some commonly used declarative mappings (in the structure ):
C ++: String Array
Wchar_t comments [1, 120];
C #:
[Financialas (unmanagedtype. byvaltstr, sizeconst = 120)]
Public String comments;

C ++: structure member
Version_info ver;
C #
Publicstructversioninfo ver;

C ++: function pointer Declaration
Pfoo; // For details, seeArticlePrevious section
C #:
Publicintptr pfoo; // It can also be public int pfoo;
// You can use the corresponding functions of the preceding dllwrapper class to obtain the corresponding delegate instance for different declaration methods.

If Union is used in the structure, fieldoffset can be used to specify the specific position.

3. Delegate statement:

When a DLL function written in C ++ needs to pass out a structure through the pointer: See the following statement:
Void getversioninfo (version_info * ver );
For the structure declared as class in C # (when version_info is declared as Class)
Delegate voidgetversioninfo (version_info ver );
If the structure declaration is struct, use the following statement:
Delegate voidgetversioninfo (refversion_info ver );
Note: The ref keyword should be used.

If the DLL function needs to input a string, for example:
Bool _ stdcall jingzhongrong1 (const wchar_t * lpfilename, int * filenum );
When using delegation to call a function, you should declare the delegate in C # as follows:
Delegate bool jingzhongrong1 (
[Financialas (unmanagedtype. lpwstr)] string filename,
Ref int filenum );
Note: You should use [financialas (unmanagedtype. lpwstr)] and string for declaration.

If You Want To output a string in the DLL function, for example,
void _ stdcall jingzhongrong2 (
wchar_t * lpfilename, // The string to be passed out
int * length);
WE declare the delegate as follows:
// use a string that is passed out of the parameters of the delegate function.
// the statement should be as follows, make sufficient space for stringbuilder before calling
delegate void jingzhongrong2 (
[managedas (unmanagedtype. lpwstr)] stringbuilder lpfilename,
ref int length,
);
before using a function, declare sufficient space for stringbuilder to store strings:
stringbuilder filename = new stringbuilder (filenamelength);

Related Article

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.