There are many methods for calling the function exported from Win32 DLL in C #. This article will summarize.
There are two possible cases:
- DLL file name and function name are known during compilation
- The DLL file name (function name) can be obtained only during runtime)
DLL file name known during compilation
In this case, you can simply use the Pinvoke mechanism, such:
[System. Runtime. InteropServices. DllImport ("kernel32.dll")]
Public static extern bool Beep (uint freq, uint time );
The DLL file name can be obtained only during runtime.
There are two solutions:
- First, we can think of using LoadLibrary and GetProcAddress in Win32 API to dynamically call the functions in DLL like in C/C ++. I will not elaborate on them here;
- Second, consider how to use DllImport dynamically. It is easy to use Reflection & Emit in. Net to dynamically generate a Pinvoke function, as shown in the following example:
Code
1 /// <summary>
2 // obtain the functions in the DLL
3 /// </summary>
4 // <param name = "dllName"> DLL file name (PATH). If the DLL name is in the path environment variable or in the current directory, you can directly specify the DLL name, otherwise, the path information should be included. </param>
5 // <param name = "methodName"> function name </param>
6 /// <param name = "returnType"> return type </param>
7 // <param name = "paramTypes"> parameter type. If no parameter exists, it is null. </param>
8 // <param name = "declareCallingConvertions"> call conventions of the generated function </param>
9 // <param name = "nativeCallingConvertions"> DLL function call conventions </param>
10 /// <param name = "nativeCharSet"> character set </param>
11 /// <returns> indicates the MethodInfo of the specified function in the specified DLL, which is a static method </returns>
12 public static MethodInfo GetMethodInfoInDll (string dllName, string methodName,
13 Type returnType, Type [] paramTypes,
14 CallingConventions declareCallingConvertions,
15 System. Runtime. InteropServices. CallingConvention nativeCallingConvertions,
16 System. Runtime. InteropServices. CharSet nativeCharSet)
17 {
18 AssemblyName assemblyName = new AssemblyName ("Assembly" + Environment. TickCount );
19 AssemblyBuilder assemblyBuilder = AppDomain. CurrentDomain. DefineDynamicAssembly (assemblyName, AssemblyBuilderAccess. Run );
20 ModuleBuilder moduleBuilder = assemblyBuilder. Defin