All articles(网络文学目录) All Pictures(图片目录) All Softwares(软件目录)

 
在C#中动态调用native,dll的导出函数_[Asp.Net教程]

Writer: delv Article type: Programming skills(编程技巧) Time: 2014/1/8 7:03:49 Browse times: 383 Comment times: 0

在C#中动态调用native,dll的导出函数_[Asp.Net教程]


Head photo

Go homepage
Upload pictures
Write articles

在C#中动态调用native dll的导出函数_[Asp.Net教程]

在 C++ 中我们能够通过 LoadLibrary, GetProcAddress 来动态调用 dll 的导出函数.
在 C# 中也能够用这样的方式吗?
在 DotNet 2.0 里面这样是可以的, 这完全得益于 2.0新增的一个函数
Marshal.GetDelegateForFunctionPointer 方法
此方法在 .NET Framework 2.0 版中是新增的。

将非托管函数指针转换为委托。
实例代码如下:


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

来源:网络





There are 0 records,
Comment:
Must be registered users to comment(必须是注册用户才能发表评论)

Disclaimer Privacy Policy About us Site Map
Copyright ©2011-
uuhomepage.com, Inc. All rights reserved.