Call the native DLL export function dynamically in C #

Source: Internet
Author: User

In C ++, we can use loadlibrary and getprocaddress to dynamically call the DLL export function.
Can this method be used in C?
This is acceptable in DOTNET 2.0, thanks to a new function in 2.0.
Marshal. getdelegateforfunctionpointer Method
This method is added in. NET Framework 2.0.

Converts an unmanaged function pointer to a delegate.
The instance code is as follows:

Public Delegate int msgbox (INT hwnd, string MSG, string CPP, int OK );

[Dllimport ("Kernel32")]
Public static extern int getprocaddress (INT handle, string funcname );
[Dllimport ("Kernel32")]
Public static extern int loadlibrary (string funcname );
[Dllimport ("Kernel32")]
Public static extern int freelibrary (INT handle );

Private Static delegate getaddress (INT dllmodule, string functionname, type T)
{
Int ADDR = getprocaddress (dllmodule, functionname );
If (ADDR = 0)
Return NULL;
Else
Return marshal. getdelegateforfunctionpointer (New intptr (ADDR), t );
}

Private void button#click (Object sender, eventargs E)
{
Int huser32 = 0;
Huser32 = loadlibrary ("user32.dll ");
Msgbox mymsg = (msgbox) getaddress (huser32, "messageboxa", typeof (msgbox ));
Mymsg (this. Handle. toint32 (), txtmsg. Text, txttitle. Text, 64 );
Freelibrary (huser32 );
}

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.