You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在x86/x64混合环境中让AnyCPU DLL适配SQLite依赖

问题描述

我有一个目标平台为AnyCPU的托管代码DLL,该DLL会调用SQLite。我会在x64应用程序或x86服务器中调用这个DLL。SQLite需要对应x64或x86架构的原生DLL——SQLite.Interop.DLL:
SQLite架构对应DLL示意图

请问如何确保在任何情况下都能链接到合适的DLL?

编辑: 之前的图片有误,已更换。


解决方案

以下是几种可靠的实现方式,确保AnyCPU托管DLL能自动匹配对应架构的SQLite.Interop.DLL:

1. 使用官方SQLite NuGet包(推荐)

直接安装System.Data.SQLite或Microsoft.Data.Sqlite官方NuGet包,这些包会自动处理架构适配:

  • 安装后,NuGet会在项目中自动生成x86和x64目录,分别放入对应架构的SQLite.Interop.DLL
  • 构建时,包会根据运行时的进程架构,自动将对应版本的原生DLL复制到输出目录,无需手动配置

2. 手动配置文件与加载逻辑

如果需要手动管理原生DLL,按以下步骤操作:

  • 在项目根目录创建x86和x64两个文件夹,分别放入对应架构的SQLite.Interop.DLL
  • 选中这两个DLL文件,在属性窗口设置:
    • 复制到输出目录:选择如果较新则复制
    • 生成操作:设置为内容
  • 在托管DLL的初始化代码中,根据当前进程架构加载对应DLL:
using System;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;

public static void InitializeSQLite()
{
    var currentAssemblyDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
    var targetArch = Environment.Is64BitProcess ? "x64" : "x86";
    var interopDllPath = Path.Combine(currentAssemblyDir, targetArch, "SQLite.Interop.DLL");
    
    // 加载原生DLL
    NativeLibrary.Load(interopDllPath);
}
  • 注意:必须在调用任何SQLite相关方法前,执行上述初始化代码

3. 利用程序集解析事件动态加载

通过注册程序集解析事件,在运行时自动查找并加载对应架构的DLL:

using System;
using System.Reflection;
using System.IO;

public static void SetupSQLiteResolver()
{
    AppDomain.CurrentDomain.AssemblyResolve += (sender, resolveArgs) =>
    {
        if (resolveArgs.Name.StartsWith("SQLite.Interop,"))
        {
            var targetArch = Environment.Is64BitProcess ? "x64" : "x86";
            var dllPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, targetArch, "SQLite.Interop.DLL");
            return Assembly.LoadFrom(dllPath);
        }
        return null;
    };
}
  • 在应用程序启动阶段调用该方法,确保事件注册完成后再使用SQLite功能

内容的提问来源于stack exchange,提问作者Bernd Morgeneyer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 03:11:03