c#中动态装载dll

记得很久前有个人让我解决这么一个事情,他的一个c动态连接库里面有个静态变量,每次调用这个方法的时候,就自动增加,他想在特定的时候,为了恢复这个静态变量的初值,动态卸了这个动态库,然后重新加载。(该动态库不能改动)

c#里面要用到动态库,需要使用DllImport,但是这个是全局的东西,不能像动态load/unload assembly所使用的AppDomain的方法。

这样就想到了API: LoadLibrary, GetProcAddress, 和FreeLibrary方法。
  [DllImport("kernel32",EntryPoint="LoadLibrary",SetLastError=true)]
  static extern IntPtr LoadLibrary(string lpLibName);

  [DllImport("kernel32",EntryPoint="GetProcAddress",SetLastError=true)]
  static extern IntPtr GetProcAddress(IntPtr hModule, string lpProcName);

  [DllImport("kernel32",EntryPoint="FreeLibrary",SetLastError=true)]
  static extern bool FreeLibrary(IntPtr hModule);

然后调用
   IntPtr hModule = IntPtr.Zero;
   IntPtr pfn = IntPtr.Zero;

   // Load the library and get a pointer to the function 
   hModule = LoadLibrary("ADll.dll"); 
   pfn = GetProcAddress(hModule, "GetValue"); 
然后就麻烦了,知道这个函数的入口地址,我怎么调用这个函数呢,我一直不知道这个用c#怎么解决,最后就写了一段IL代码。
.assembly extern mscorlib {}
.assembly Wrapper {}

.class public Wrapper
{
     .method public static int32 SomeMethod(native int pfn)
    {
        .maxstack 2
        .locals (int32 V_0)
        ldarg.0 // Push pfn onto the execution stack
        calli unmanaged stdcall int32()
        stloc.0
        ldloc.0
        ret
    }
}
把这个.il文件编译成dll
然后代码接着写
   // Make call to function pointer
   int i = Wrapper.SomeMethod(pfn);

   MessageBox.Show(this, i.ToString());
 
   FreeLibrary(hModule);
问题就解决了。

 
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值