【问题标题】:Reload a DLL which has been imported with DllImport重新加载已使用 DllImport 导入的 DLL
【发布时间】:2012-12-07 16:39:53
【问题描述】:

我的 C# 应用程序 (.NET Framework 4.0) 使用以下代码导入外部非托管 DLL:

[DllImport("myDLL.dll"), EntryPoint="GetLastErrorText"]
private static extern IntPtr GetLastErrorText();

不幸的是,第三方 DLL 中似乎存在错误。作为一种解决方法,我需要卸载 DLL 并在之后重新加载它。我怎样才能做到这一点?我看过几篇文章,但它们都在谈论托管 DLL。

【问题讨论】:

    标签: c# .net dllimport


    【解决方案1】:

    您可以在管理对它的访问的库周围编写一个包装器。然后您可以使用本机方法来调用该库。看看this 博文。

    【讨论】:

      【解决方案2】:

      我认为您需要继续使用 LoadLibrary/FreeLibrary/GetProcAddress,如 Difference between dllimport and getProcAddress 所示:下面的缩写示例(无错误处理):

         [UnmanagedFunctionPointer(CallingConvention.StdCall)]
         private delegate Bool BarType(Byte arg); 
         ...
         IntPtr pDll= LoadLibrary("foo.dll");
         IntPtr pfunc = GetProcAddress(pDll, "bar");
         BarType bar = (BarType)Marshal.GetDelegateForFunctionPointer(pFunc, typeof(BarType));
         var ok = bar(arg);
         FreeLibrary(pDll);
      

      【讨论】:

        【解决方案3】:

        您可以尝试使用LoadModule(来自WinAPI)而不是使用DllImport 导入DLL,然后使用GetProcAddressFreeLibrary 来执行您需要的调用函数它并卸载/重新加载它。

        See here.

        如果您使用 C++/CLR 将 C# 和非托管 DLL 粘合在一起,可能会更漂亮/易于管理。

        【讨论】:

          猜你喜欢
          • 2011-01-27
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-12-12
          • 2016-08-09
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多