C#在调用非托管动态库时,经常需要实时卸载动态库,本例演示如何加载、获取方法委托、卸载动态库:
[DllImport("Kernel32.dll")]
public static extern int LoadLibrary(string lpFileName);
[DllImport("Kernel32.dll")]
public static extern bool FreeLibrary(int hModule);
[DllImport("Kernel32.dll")]
public static extern IntPtr GetProcAddress(int hModule, string lpProcName);
public delegate int readcard(int ai_czlx, [MarshalAs(UnmanagedType.LPArray)]byte[] errmsg);
public delegate int writecard(int ai_czlx, byte[] ac_data, [MarshalAs(UnmanagedType.LPArray)]byte[] errmsg);
public unsafe static string Read()
{
int hLib = LoadLibrary("lib\\rdcard.dll");
IntPtr ptr = GetProcAddress(hLib, "readcard");
readcard myfunc = (readcard)Marshal.GetDelegateForFunctionPointer(ptr, typeof(readcard));
try
{
unsafe
{
int i = -1;
byte[] bytes = new byte[200];
try
{
i = myfunc(2, bytes);
}
catch (SEHException ex)
{
throw ex;
}
catch (Exception ex)
{
throw ex;
}
string res = Encoding.Default.GetString(bytes);
return res;
}
}
finally
{
FreeLibrary(hLib);
}
}
public unsafe static int Write(string writeContent)
{
int hLib = LoadLibrary("lib\\rdcard.dll");
IntPtr ptr = GetProcAddress(hLib, "writecard");
writecard myfunc = (writecard)Marshal.GetDelegateForFunctionPointer(ptr, typeof(writecard));
try
{
unsafe
{
byte[] bytes = new byte[200];
string result = writeContent;
byte[] results = Encoding.Default.GetBytes(result);
int j = -1;
try
{
j = myfunc(2, results, bytes);
}
catch
{
}
return j;
}
}
finally
{
FreeLibrary(hLib);
}
}