2

我正在开发一个使用反射加载插件的 .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 的程序集?

4

3 回答 3

1

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

  [DllImport("plugin.dll")]
  public static extern void SomeFunction();
于 2009-07-10T21:54:03.377 回答
1

您是否尝试过 Assembly.LoadFile()?

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

于 2009-07-10T22:03:40.330 回答
1

您想要以下内容:

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 中,您就无法卸载它。

于 2009-07-10T22:15:23.053 回答