我有一个32位和64位的dll,现在我希望我的exe从解决方案平台调用dll,这意味着当x64设置时,64位的dll将调用。为此,我声明了一个函数GetPlatform()。
Public Function GetPlateform() As String
Dim var1 As String
If (IntPtr.Size = 8) Then
var1 = hellox64
Else
var1 = hello
End If
Return var1
End Function
和何时加载表单这个var1被赋值给var,最后。
Public Declare Function function1 Lib "var" (ByVal Id As Integer) As Integer
但是当我调试代码"DllNotFoundException"发生。注意: dll在vc++中
将本机dll存储到子文件夹中,并通过相应地填充PATH
进程环境变量,向Library Loader提示要加载的正确版本的路径。
例如,给定这个树形布局…
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
将根据IntPtr的大小动态绑定到本地代码的32位或64位版本(更多关于这一点,请参阅Scott Hanselman或StackOverflow问题)。
注释1:当两个版本的dll具有相同的名称或如果您不愿意复制每个外部引用时,此解决方案特别有用。
注2:这已经在LibGit2Sharp中成功实现了。
不,您不能在lib语句中动态创建对DLL的引用。但是,您可能(免责声明:没有尝试过)能够创建两个引用并在代码中调用适当的引用。
Public Declare Function Function132 Lib "My32BitLib.DLL" Alias "function1" (ByVal Id As Integer) As Integer
Public Declare Function Function164 Lib "My64BitLib.DLL" Alias "function1" (ByVal Id As Integer) As Integer
您将需要在平台上进行分支,并根据平台调用适当的别名函数名(Function132或Function164)。