将您的本机 dll 存储到子文件夹中,并通过使用要加载的正确版本的路径相应地填充进程环境变量来提示Library Loader 。PATH
例如,给定这个树形布局......
Your_assembly.dll
|_NativeBinaries
|_x86
|_your_native.dll
|_amd64
|_your_native.dll
...和这段代码(对不起,C#,没有 VB.Net :-/)...
internal static class NativeMethods
{
private const string nativeName = "your_native";
static NativeMethods()
{
string originalAssemblypath = new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath;
string currentArchSubPath = "NativeBinaries/x86";
// Is this a 64 bits process?
if (IntPtr.Size == 8)
{
currentArchSubPath = "NativeBinaries/amd64";
}
string path = Path.Combine(Path.GetDirectoryName(originalAssemblypath), currentArchSubPath);
const string pathEnvVariable = "PATH";
Environment.SetEnvironmentVariable(pathEnvVariable,
String.Format("{0}{1}{2}", path, Path.PathSeparator, Environment.GetEnvironmentVariable(pathEnvVariable)));
}
[DllImport(nativeName)]
public static extern int function1(int param);
[DllImport(nativeName)]
public static extern int function2(int param);
}
...function1
并且function2
将动态绑定到本机代码的 32 位或 64 位版本,具体取决于 IntPtr 的大小(更多内容请参见Scott Hanselman的这篇文章或这个StackOverflow 问题)。
注意 1:当 dll 的两个版本具有相同名称或您不愿意复制每个外部引用时,此解决方案特别有用。
注意 2:这已经在LibGit2Sharp中成功实现。