试图加载格式不正确的程序

An attempt was made to load a program with an incorrect format

本文关键字:程序 不正确 格式 加载      更新时间:2023-10-16

我正在使用c#加载c++ dll,并得到这个错误:

"类型为'System '的未处理异常。BadImageFormatException' occurred in MyApp.exe"附加信息:试图加载格式不正确的程序。(Exception from HRESULT: 0x8057000B)

我不明白为什么。c++ dll是使用vs2012向导生成的,win32应用程序,带前置的dll。它是用x64选项构建的。下面是代码:

// MyNativeDLL.cpp : Defines the exported functions for the DLL application.
//
#include "stdafx.h"
    //char* pMemoryBuffer = NULL;
    using namespace std;
    __declspec(dllexport) long  Test()
    {
        long a;
         a = 1;
         a++;
         return a;
    }
调用它的c#代码是:
[DllImport("C:\MyNativeDLL\x64\Debug\MyNativeDLL.dll",  EntryPoint = "Test")]
private extern static int Test();
void doJob()
{
   long a = Test();  // exception thrown here
}
c#代码是用任意CPU选项构建的,它正在加载x64本地dll。我想知道我哪里做错了?我已经试了很久了,但是真的卡住了。谢谢!

当我使用win32选项编译本机dll时,并设置正确的dll路径,它加载成功。但是当我用x64选项编译本机dll时,用正确的路径加载,加载失败。

正如你所说: c++ dll是使用vs2012向导生成的,win32应用程序,带前置的dll。它是用x64选项

构建的

DLL和exe必须都是32位,或者都是64位。