System.BadImageFormatException 使用任何 cpu 编译时

System.BadImageFormatException when compiled using any cpu

当我使用 "Any CPU" 编译应用程序时,每当我尝试使用 Firebird 嵌入式 dll 打开连接时,我都会得到 System.BadImageFormatException(不要问我为什么我仍在使用这个遗留数据库。不是我的选择)

然后我想一定是dll只支持32位模式。所以我尝试使用 x86 进行编译,这次确实 运行 没问题。

然而,当我使用 x64 编译时,应用程序仍然 运行 没问题。这让我感到困惑,因为它清楚地表明 dll 能够以 64 位模式加载。

我做了更多测试,结果如下:

任意 CPU:64 位进程。 System.BadImageFormatException
x86:32 位进程。运行良好
x64:64 位进程。运行良好
任何 CPU(首选 32 位):32 位进程。运行正常

我认为 Any CPU 唯一的魔力是它在启动期间选择是否以 32/64 位模式启动进程。如果应用程序 运行 在严格的 64 位模式下运行良好,那么我希望任何 CPU 到 运行 在同一台 64 位机器上运行良好。

我更愿意使用 Any CPU(不喜欢 32 位标志),因为它使分发更容易。

可能导致异常的原因是什么,有没有办法处理它?

编辑:
所以我尝试使用反射来获取程序集信息,这是我收到的错误消息

Exception calling "GetAssemblyName" with "1" argument(s): "Could not load file or assembly 'fbembed.dll' or one of its dependencies. The module was expected to contain an assembly manifest." At line:1 char:1 + [reflection.assemblyname]::GetAssemblyName("${pwd}\fbembed.dll") | fl + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [], MethodInvocationException + FullyQualifiedErrorId : BadImageFormatException

在检查了 dll 的 header 后,发现 Nuget 是施展魔法的那个。如果我将目标设置为 x86/x64,nuget 将在编译期间包含相应版本的 dll。

但是如果我以 "Any CPU" 为目标,nuget 将选择 dll 的 x86 版本。因此,如果我尝试以 64 位模式启动我的应用程序,它将抛出 BIFE。