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

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

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

None.gif public   delegate   int  MsgBox( int  hwnd, string  msg, string  cpp, int  ok);
None.gif
None.gif        [DllImport(
" Kernel32 " )]
None.gif        
public   static   extern   int  GetProcAddress( int  handle, String funcname);
None.gif        [DllImport(
" Kernel32 " )]
None.gif        
public   static   extern   int  LoadLibrary(String funcname);
None.gif        [DllImport(
" Kernel32 " )]
None.gif        
public   static   extern   int  FreeLibrary( int  handle);
None.gif
None.gif        
private   static  Delegate GetAddress( int  dllModule,  string  functionname, Type t)
ExpandedBlockStart.gifContractedBlock.gif        
dot.gif {
InBlock.gif            
int addr = GetProcAddress(dllModule, functionname);
InBlock.gif            
if (addr == 0
InBlock.gif                
return null
InBlock.gif            
else 
InBlock.gif                
return Marshal.GetDelegateForFunctionPointer(new IntPtr(addr), t);
ExpandedBlockEnd.gif        }

None.gif
None.gif        
private   void  button1_Click( object  sender, EventArgs e)
ExpandedBlockStart.gifContractedBlock.gif        
dot.gif {
InBlock.gif            
int huser32 = 0;
InBlock.gif            huser32 
= LoadLibrary("user32.dll");         
InBlock.gif            MsgBox mymsg 
= (MsgBox)GetAddress(huser32, "MessageBoxA"typeof(MsgBox));
InBlock.gif            mymsg(
this.Handle.ToInt32(), txtmsg.Text, txttitle.Text , 64);
InBlock.gif            FreeLibrary(huser32);
ExpandedBlockEnd.gif        }

apimsg.jpg

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值