[Original] how to load dynamic libraries, obtain method delegation, and unload dynamic libraries

Source: Internet
Author: User

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 );
}
}

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.