SQLite BadImageFormatException 处理

问题背景#

在一个 MFC 嵌 WPF 的项目中,WPF 使用了 sqlite 数据库,使用的是 System.Data.SQLite.Core 这个包,SQLite.Interop.dll 文件有 x64 x86 等多个版本,
如果拷贝到 MFC 输出目录中的版本不对,就会出现这个问题。

简单来说,就是 SQLite.Interop.dll 的框架版本与主应用程序的框架版本不匹配。

解决方案1#

如果主应用程序的框架是确定的,可以直接使用 System.Data.SQLite.x64 或者 System.Data.SQLite.x86 这两个 nuget 包,直接解决问题。

问题是会引入很多其它可能不需要的包,而且固定版本,少了一点灵活性。

解决方案2#

在编译后通过脚本自动拷贝

System.Data.SQLite: Downloads Page

Using XCOPY deployment in conjunction with the native library pre-loading feature, especially for customer machines, is highly recommended.

<!-- 将 sqlite 依赖按照 x64/x86 框架,复制到 MFC 输出目录 -->
<Target Name="CopySqliteDllToOutput" AfterTargets="Build" Condition="'$(Configuration)' == 'Debug'">
  <PropertyGroup>
    <x64Source>$(OutputPath)runtimes\win-x64\native\SQLite.Interop.dll</x64Source>
    <x86Source>$(OutputPath)runtimes\win-x86\native\SQLite.Interop.dll</x86Source>
    <TargetDir>$(ProjectDir)..\xxx\xxx\..</TargetDir>
    <x64Target>$(TargetDir)x64\SQLite.Interop.dll</x64Target>
    <x86Target>$(TargetDir)x86\SQLite.Interop.dll</x86Target>
    <ToDeleteFile>$(TargetDir)SQLite.Interop.dll</ToDeleteFile>
  </PropertyGroup>

  <!-- 创建目标目录 -->
  <MakeDir Directories="$(TargetDir)x64" />
  <MakeDir Directories="$(TargetDir)x86" />

  <!-- 检查是否存在 SQLite.Interop.dll 源文件,如果不存在则报错 -->
  <Error Condition="!Exists('$(x64Source)')" Text="x64 SQLite.Interop.dll not found at '$(x64Source)'. Build failed." />
  <Error Condition="!Exists('$(x86Source)')" Text="x86 SQLite.Interop.dll not found at '$(x86Source)'. Build failed." />

  <!-- 删除原本存在的 SQLite.Interop.dll 文件 -->
  <Delete Files="$(ToDeleteFile)" Condition="Exists('$(ToDeleteFile)')" />

  <!-- 复制 x64 版本的 DLL -->
  <Copy SourceFiles="$(x64Source)" DestinationFiles="$(x64Target)" Condition="Exists('$(x64Source)')" />
  <!-- 复制 x86 版本的 DLL -->
  <Copy SourceFiles="$(x86Source)" DestinationFiles="$(x86Target)" Condition="Exists('$(x86Source)')" />

</Target>

sqlite - System.BadImageFormatException: An attempt was made to load a program with an incorrect format. (Exception from HRESULT: 0x8007000B) at - Stack Overflow

https://www.cnblogs.com/jasongrass/p/18563483

作者:JasonGrass

出处:https://www.cnblogs.com/jasongrass/p/18563483

版权:本作品采用「署名 4.0 国际」许可协议进行许可。

posted @   J.晒太阳的猫  阅读(24)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 【.NET】调用本地 Deepseek 模型
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· DeepSeek “源神”启动!「GitHub 热点速览」
· 我与微信审核的“相爱相杀”看个人小程序副业
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库
more_horiz
keyboard_arrow_up light_mode palette
选择主题
menu
点击右上角即可分享
微信分享提示