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

人走茶凉 提交于 2019-12-13 08:18:49

问题


I am using C# loading C++ dll, and got this error:

"An unhandled exception of type 'System.BadImageFormatException' occurred in MyApp.exe" "Additional information: An attempt was made to load a program with an incorrect format. (Exception from HRESULT: 0x8057000B)

I could not figure out why. The C++ dll was generated using vs2012 wizard, win32 application, dll with pre-head. It is built with x64 option. Here is the code:

// 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;
    }

The C# code calling it is:

[DllImport("C:\\MyNativeDLL\\x64\\Debug\\MyNativeDLL.dll",  EntryPoint = "Test")]
private extern static int Test();
void doJob()
{
   long a = Test();  // exception thrown here
}

C# code is built with Any CPU option, and it is loading the x64 native dll. I wondering where I did wrong? I have been trying long, but really get stuck here. Thanks!

UPDATE When I compile my native dll using win 32 option, and set up correct dll path, it loads successfully. But when I compile my native dll with x64 options, load with correct path, the loading fails.


回答1:


As you mentioned: The C++ dll was generated using vs2012 wizard, win32 application, dll with pre-head. It is built with x64 option

The DLL and exe have to be both 32 bit, or both 64 bit.



来源:https://stackoverflow.com/questions/24459129/an-attempt-was-made-to-load-a-program-with-an-incorrect-format

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!