在 C++ 中我們能夠通過(guò) LoadLibrary, GetPRocAddress 來(lái)動(dòng)態(tài)調(diào)用 dll 的導(dǎo)出函數(shù).
在 C# 中也能夠用這樣的方式嗎?
在 DotNet 2.0 里面這樣是可以的, 這完全得益于 2.0新增的一個(gè)函數(shù)
Marshal.GetDelegateForFunctionPointer 方法
此方法在 .NET Framework 2.0 版中是新增的。
將非托管函數(shù)指針轉(zhuǎn)換為委托。
實(shí)例代碼如下:
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);
}
鏈接地址: http://rick.VEVb.com/archive/2006/07/13/apicall.html
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注