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