Dynamic invocation of C + + dynamic links in C #

Source: Internet
Author: User
Tags function prototype mscorlib

The previous article described exporting variables from DLLs, including static loading and dynamic loading.

C # calls to C + + dynamic-link libraries are also classified as static loading and dynamic loading.

Fellen's blog, "Using MFC dynamic-link library (DLL) functions in WPF", describes how C # statically loads DLLs, that is, a DLL that requires C + + code compilation to be placed in the bin directory of a C # program, and where the function is introduced into the [DllImport ("Xxx.dll ”)] 。

Because of the limitations of DLL paths, it is not very convenient to use, in C # We often configure dynamic calls to managed DLLs, such as some commonly used design patterns: Abstract Factory, Provider, strategy mode, and so on, then is it possible to dynamically invoke C + + What about dynamic links? As long as you remember in C + +, through LoadLibrary, GetProcess, freelibrary These functions can be dynamically called dynamically linked (they are included in the Kernel32.dll), then the problem is solved.

First take a look at LoadLibrary, GetProcAddress, freelibrary these three functions:

hmodule WINAPI LoadLibrary (LPCTSTR lpfilename);
Description
Loads the specified dynamic-link library and maps it to the address space used by the current process. Once loaded, you can access the resources saved in the library
return value
Lplibfilename String that specifies the name of the dynamic-link library to load. Use the same search order as specified by the lpCommandLine parameter of the CreateProcess function
Release the DLL with the FreeLibrary function once it is not required

farproc GetProcAddress (hmodule hmodule, LPCSTR lpprocname); The
Description:
GetProcAddress function retrieves the address of the output library function in the specified dynamic-link library (DLL). A
Hmodule
[in] handle to the DLL module that contains this function. The LoadLibrary, AfxLoadLibrary, or GetModuleHandle functions can return this handle.
Lpprocname
[in] contains a null-terminated string for the function name, or specifies the ordinal value of the function. If this parameter is an ordinal value, it must be at the base byte of a word, and the high byte must be 0.
Return Value:
If the function call succeeds, the return value is the address of the output function in the DLL.
If the function call fails, the return value is null. Get further error message, call function GetLastError. The
GetProcAddress function is used to retrieve the address of the output function in the DLL. The
Lpprocname pointer points to the function name, the spelling and capitalization must and the module definition file in the DLL source code (. DEF) is the same as specified in the output segment (exports). The output name of the Win32 API function may be different from the name of these functions that you call in the code, which is implicitly in the relevant SDK header file. For more information, refer to the Win32 function prototype (Win32 functions prototypes). The
Lpprocname parameter recognizes a function in a DLL by specifying an ordinal value that is associated with the function (exports segment in. def). The GetProcAddress function verifies that the specified ordinal value is between the ordinal 1 of the output and the highest ordinal value (in. def). The function uses this ordinal value as an index to read the function address from the function table, if. DEF files do not sequentially define the ordinal value of a function, such as from 1 to N (n is the function ordinal value of the output), the error will occur, and GetProcAddress will return an incorrect, non-empty address, although the specified ordinal does not have a corresponding function.
to prevent a function from being absent, the function should be specified by name rather than by ordinal value.

BOOL WINAPI FreeLibrary ( in hmodule hmodule);
Description
Releases the specified dynamic-link libraries, which were previously loaded with the LoadLibrary API function.

Using a two-step walk, the first is to introduce the above three functions and encapsulate them. Create a new class named CSharpMethod.cs. It is important to note that namespaces using System.Runtime.InteropServices must be introduced.

usingSystem;usingSystem.Collections.Generic;usingSystem.Text;usingSystem.runtime.interopservices;namespace interopdemo{ Public Static classCsharpmethod {[DllImport ("Kernel32.dll", EntryPoint ="LoadLibrary")] Public Static extern int LoadLibrary(            [MarshalAs(UNMANAGEDTYPE.LPSTR)]stringLplibfilename); [DllImport ("Kernel32.dll", EntryPoint ="GetProcAddress")] Public Static externIntPtrGetProcAddress(intHmodule, [MarshalAs(UNMANAGEDTYPE.LPSTR)]stringLpprocname); [DllImport ("Kernel32.dll", EntryPoint ="FreeLibrary")] Public Static extern BOOL FreeLibrary(intHMODULE); }}

The next step is to use it specifically:
Use the Nativemethod class to dynamically read C++dll, get a function pointer, and encapsulate the pointer as a delegate in C #. The reason is simple, there is no use of pointers in C #, as follows
int hmodule = Csharpmethod.loadlibrary (@ "C:" CppDemo.dll ");
IntPtr IntPtr = csharpmethod.getprocaddress (hmodule, "Add");

usingSystem;usingSystem.Collections.Generic;usingSystem.Text;usingSystem.runtime.interopservices;namespace interopdemo{class Program {Static voidMain (string[] args) {//1. Dynamically loading C + + DLLs            inthmodule = Csharpmethod.loadlibrary (@ "C:\CppDemo.dll");if(Hmodule = =0)return;//2. Reading function PointersIntPtr IntPtr = csharpmethod.getprocaddress (hmodule,"Add");//3. Encapsulating a function pointer as a delegateAdd addfunction = (add) marshal.getdelegateforfunctionpointer (INTPTR,typeof(ADD));//4. TestingConsole.WriteLine (AddFunction (1,2));        Console.read (); }Delegate intADD (intAintb); }}

Marshal was used in the appeal code. GetDelegateForFunctionPointer method, the following is a brief introduction.
Function: Converts an unmanaged function pointer to a delegate.
Namespaces: System.Runtime.InteropServices
Assembly: mscorlib (in mscorlib.dll)
Syntax: public static Delegate GetDelegateForFunctionPointer (IntPtr ptr, Type t)
Parameter: PTR is the unmanaged function pointer to be converted, and T is the type of delegate to return.
Return value: The type is a System.Delegate delegate instance and can be cast to the appropriate delegate type.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Dynamic invocation of C + + dynamic links in C #

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.