gpt4 book ai didi

.net - 如何根据客户端架构动态加载x86/x64版本的SQLite3.DLL?

转载 作者:行者123 更新时间:2023-12-03 17:15:21 24 4
gpt4 key购买 nike

我正在尝试在运行时动态加载适当的 x86/x64 版本的 SQLite3.DLL,以便与 Devart.SQLite.DLL 一起使用。我无法控制事先将适当版本的 DLL 安装到应用程序根目录,因此我必须以某种方式尝试从应用程序根目录的/x86 或/x64 子目录中获取正确的版本。

关于如何实现这个的任何想法?诚然,我完全迷失在这里。到目前为止我的代码是:

Public Sub New()
LoadAssembly("sqlite3.dll", True)
End Sub

Private Function GetAssemblyPath(ByVal assembly As String, ByVal version As String) As String
Return Path.GetDirectoryName(Reflection.Assembly.GetExecutingAssembly().Location) & "\" & version & "\" & assembly
End Function ' GetAssemblyName

<Runtime.InteropServices.DllImportAttribute("kernel32.dll", EntryPoint:="LoadLibraryW")> _
Public Shared Function LoadLibraryW(<Runtime.InteropServices.InAttribute()> <Runtime.InteropServices.MarshalAsAttribute(Runtime.InteropServices.UnmanagedType.LPWStr)> lpLibFileName As String) As IntPtr
End Function

Private Sub LoadAssembly(ByVal myAssembly As String, Optional ByVal doLoadLibrary As Boolean = False)
Dim an As AssemblyName
Dim filename As String
Dim version As String

If UIntPtr.Size = 8 Then version = "x64" Else version = "x86"
filename = GetAssemblyPath(myAssembly, version)

Try
If doLoadLibrary Then
HostLog.WriteEntry(filename, EventLogEntryType.Information)
Dim ptr As IntPtr = LoadLibraryW(filename)
HostLog.WriteEntry(ptr.ToString(), EventLogEntryType.Information)
Else
an = AssemblyName.GetAssemblyName(filename)
AppDomain.CurrentDomain.Load(an)
End If
Catch ex As Exception
HostLog.WriteEntry(ex.Message, EventLogEntryType.Error)
End Try
End Sub ' LoadAssembly

编辑如评论中所述,我未能指定在尝试加载 sqlite3.dll 时收到的实际错误。事实证明,我的 App.Config 中缺少以下内容:

<system.data>
<DbProviderFactories>
<remove invariant="Devart.Data.SQLite" />
<add name="dotConnect for SQLite"
invariant="Devart.Data.SQLite"
description="Devart dotConnect for SQLite"
type="Devart.Data.SQLite.SQLiteProviderFactory, Devart.Data.SQLite, Version=4.2.122.0, Culture=neutral, PublicKeyToken=09af7300eec23701" />
</DbProviderFactories>
</system.data>

将此添加到 App.Config 后,我之前的代码示例按预期工作。感谢大家的帮助。

最佳答案

您可以创建一个具有两个实现的接口(interface)。一个 x86 实现和一个 x64 实现。可以说 [DllImport("x86version.dll")]Bob(string s); 也可以说 [DllImport("x64version.dll")]Bob(string s);

例子:

public interface ISQLite
{
public void Foo();
}

public class SQLite32 : ISQLite
{
[DllImport("x86/SQLite3.dll")]
private void foo();
public void Foo()
{
foo();
}
}

public class SQLite64 : ISQLite
{
[DllImport("x64/SQLite3.dll")]
private void foo();
public void Foo()
{
foo();
}
}

public static class SQLiteLoader
{
public static ISQLite GetSQLite()
{
if(System.Environment.Is64BitOperatingSystem)
return new SQLite64();
else
return new SQLite32();
}
}

关于.net - 如何根据客户端架构动态加载x86/x64版本的SQLite3.DLL?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13654280/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com