0

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.

Ono
  • 1,357
  • 3
  • 16
  • 38
  • 2
    check if the process is 32 bit while the dll is 64 bit, or vs verse – Matt Jun 27 '14 at 19:10
  • why return type is kept `int`? What happens when you keep target platform as `x64` for your C# application? – Hassan Jun 27 '14 at 19:14
  • It seems my application is 32 because it has a 32* in windows process monitor. But I create my application using C#, so how do I change it to x64? – Ono Jun 27 '14 at 19:29
  • @HassanNisar It throws same error. – Ono Jun 27 '14 at 19:37
  • @Ono, may be not relevant but can you please tell why using `private extern static int Test();` instead of `private extern static long Test();`? – Hassan Jun 27 '14 at 19:43
  • @HassanNisar 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. – Ono Jun 27 '14 at 19:48

1 Answers1

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.

Matt
  • 6,010
  • 25
  • 36
  • How do I make this happen? I thought for C#, just build with Any CPU? But that gives the error I mentioned in the thread. – Ono Jun 27 '14 at 19:36