惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

A
About on SuperTechFans
博客园 - 聂微东
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
博客园 - 司徒正美
宝玉的分享
宝玉的分享
美团技术团队
量子位
The Cloudflare Blog
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
IT之家
IT之家
爱范儿
爱范儿
J
Java Code Geeks
博客园 - Franky
Last Week in AI
Last Week in AI
B
Blog
H
Hackread – Cybersecurity News, Data Breaches, AI and More
I
InfoQ
GbyAI
GbyAI
Recent Announcements
Recent Announcements
小众软件
小众软件
H
Help Net Security
Microsoft Azure Blog
Microsoft Azure Blog
MyScale Blog
MyScale Blog

博客园 - 什么都不知道

DataSet的Xml序列化问题 VB.NET的一个小问题 Access is denied的问题 - 什么都不知道 存储过程output参数问题 SQL Server的效率? datagrid刷新问题 使用Visio DrawingControl的应用开发(补) 突起效果的Label WinForm下TextBox的数据绑定和更新 使用Radio按钮选择DataGrid行 如何在运行时加载不处于应用程序目录下的assembly 使用VSA给程序加上脚本支持 删除所有Windows组件 在ASP.NET中嵌入wml标记 处理大型xml文件 RedirectToMobilePage的问题 使用Visio 2003 Drawing Control开发应用(3)(4) 使用Visio 2003 Drawing Control开发应用(2) 使用Visio 2003 Drawing Control开发应用(1)
c#中动态装载dll
什么都不知道 · 2004-09-03 · via 博客园 - 什么都不知道

记得很久前有个人让我解决这么一个事情,他的一个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);
问题就解决了。