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

次のようなものが必要です。

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 に答える