【问题标题】:How do I load an assembly that references a Win32 DLL?如何加载引用 Win32 DLL 的程序集?
【发布时间】:2009-07-10 21:42:54
【问题描述】:

我正在开发一个使用反射加载插件的 .NET 应用程序。我的插件是 C# 类库。问题是我的一些插件引用了传统的 Win32 DLL,而 C# 盲目地尝试加载依赖项,就好像它们是 .NET DLL 一样。

这是我加载插件的方式:

string fileName = "plugin.dll";
Assembly.LoadFrom(fileName);

我收到一个System.BadImageFormatException,其中包含以下消息:

Could not load file or assembly 'plugin.dll' or one of its dependencies.
The module was expected to contain an assembly manifest.

如何以编程方式加载引用 Win32 DLL 的程序集?

【问题讨论】:

    标签: c# .net plugins assembly.load


    【解决方案1】:

    如果您只需要 dll 中的一些功能,您可以这样做:

      [DllImport("plugin.dll")]
      public static extern void SomeFunction();
    

    【讨论】:

      【解决方案2】:

      您尝试过 Assembly.LoadFile() 吗?

      请记住,LoadFile 不会将文件加载到 LoadFrom 上下文中,也不会像 LoadFrom 方法那样使用加载路径解析依赖项。 LoadFile 在这种有限的场景中很有用,因为 LoadFrom 不能用于加载具有相同标识但不同路径的程序集;它只会加载第一个这样的程序集

      【讨论】:

        【解决方案3】:

        你想要类似下面的东西:

        foreach (string filePath in Directory.GetFiles(path, "*.DLL"))
        {
            try
            {
                _assemblies.Add(Assembly.LoadFile(filePath));
            }
            catch (FileNotFoundException)
            {
                // Attempted to load something with a missing dependency - ignore.
            }
            catch (BadImageFormatException)
            {
                // Attempted to load unmanaged assembly - ignore.
            }
        }
        

        您仍然需要确保您的托管依赖项或本机依赖项可用,并且不会意外加载本机 DLL。对于托管程序集,可能需要更改 app.config 中的 .net 探测路径以确保找到它们:

        <configuration>
            <runtime>
                <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
                    <probing privatePath="modules"/>
                </assemblyBinding>
            </runtime>
        

        理想情况下,您希望将插件放在单独的目录中,因为对许多您不感兴趣的程序集调用 LoadFile 很慢,并且一旦您将程序集加载到 AppDomain 中,您就无法卸载它。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-04-25
          • 1970-01-01
          相关资源
          最近更新 更多