用户名: 密码: 验证码:           网站地图  高级搜索  RSS订阅  收藏本站
您的位置:主页 > 程序编程 > C# >

在C#中动态调用native dll的导出函数

[ 来源:BLOG | 作者: | 更新日期:2008-3-21 09:41:25 | 人气: | 评论 0 条 ]

  在 C 中我们能够通过 LoadLibrary, GetProcAddress 来动态调用 dll 的导出函数.

  在 C# 中也能够用这样的方式吗?

  在 DotNet 2.0 里面这样是可以的, 这完全得益于 2.0新增的一个函数,Marshal.GetDelegateForFunctionPointer 方法。此方法在 .NET Framework 2.0 版中是新增的。

  将非托管函数指针转换为委托。

  实例代码如下: 复制于jc567.cn

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));
文章来源于www.jc567.cn

 mymsg(this.Handle.ToInt32(), txtmsg.Text, txttitle.Text , 64);
 FreeLibrary(huser32);
}


Tags:在C#中动态调用native,dll的导出函数
您的评论
用户名: 新注册) 密码: 匿名评论 [所有评论]

·用户发表意见仅代表其个人意见,并且承担一切因发表内容引起的纠纷和责任
·本站管理人员有权在不通知用户的情况下删除不符合规定的评论信息或留做证据
·请客观的评价您所看到的资讯,提倡就事论事,杜绝漫骂和人身攻击等不文明行为