C # When calling an unmanaged dynamic library, you often need to detach the dynamic library in real time. This example shows how to load, obtain method delegation, and detach a dynamic library:
[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, [financialas (unmanagedtype. lparray)] Byte [] errmsg );
Public Delegate int writecard (INT ai_czlx, byte [] ac_data, [financialas (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 [1, 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 = getprocaddress (hlib, "writecard ");
Writecard myfunc = (writecard) Marshal. getdelegateforfunctionpointer (PTR, typeof (writecard ));
Try
{
Unsafe
{
Byte [] bytes = new byte [1, 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 );
}
}