Incorrect format Exception while trying to call C+

2020-04-17 07:40发布

问题:

I'm Using C# WPF.
I have a C++ test dll as follow:
.h:

extern "C" __delspec(dllexport) void TestMethod();

.cpp file:

extern "C"
{
    __delspec(dllexport) void TestMethod()
    {
        MessageBox(0, L"Test", L"Test", MB_ICONINFORMATION);
    }
}

C# Code:

[DllImport("DllTest.dll", EntryPoint = "TestMethod")]
public static extern void TestMethod();

And when i'm trying to call to TestMethod i got exception:

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

What i'm doing wrong?
Thanks!


回答1:

This seems to be 32bit/ 64 bit problem. Seems like your C++ dll and C# calling assembly are built for different platform targets. Try compiling both for the same platform (either x86 or x64) and then calling the function.