To dynamically invoke the native DLL's exported function in C #

Source: Internet
Author: User
Dynamic | function

In C + + We can invoke DLL's exported function dynamically through LoadLibrary, GetProcAddress.
Can this be done in C # as well?
In Dotnet 2.0, this is OK, thanks to the 2.0 new function.
Marshal.getdelegateforfunctionpointer method
This method is new in the. NET Framework version 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 Button1_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.