Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BadImageFormatException

Tags:

c++

c#

i was working with invoking C++ Dlls into C# and ran into a problem

C++ function:

    int _declspec(dllexport) CompressPacket(unsigned char *buff, int offset, int len);

C# function:

    [DllImport("HuffCompress.dll")]
            private static extern unsafe int HuffCompress(ref byte[] buff, int offset, int len);

    ...

    private unsafe byte[] CompressPacket(byte[] packet)
    {
        int len = HuffCompress(ref packet, 12, packet.Length-12);
        byte[] compressed = new byte[len];
        for (int i = 0; i < len; i++)
            compressed[i] = packet[i];
        return compressed;
    }

when

int len = HuffCompress(ref packet, 12, packet.Length-12);

is run, i get a BadImageFormatException

As the C# editor is the VSC# Express, it doesn't compile 64 bit programs, so i'm unsure to the problem Any ideas would be great

like image 940
Qwerty01 Avatar asked Feb 04 '26 02:02

Qwerty01


1 Answers

The missing Platform Target setting in the Express edition is almost certainly your problem. You'll have to edit your project's .csproj file by hand. Run notepad.exe and open the .csproj file. Locate the property group that looks like this:

 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">

and add this line:

    <PlatformTarget>x86</PlatformTarget>

Repeat for the Release configuration group, just below that.

Your next problem is the name of the function, it is decorated if you compiled it in C++. Declare it like this:

 extern "C" __declspec(dllexport) 
 int  __stdcall HuffCompress(unsigned char *buff, int offset, int len);

And your C# declaration is wrong, drop the ref keyword on the 1st argument.

like image 128
Hans Passant Avatar answered Feb 06 '26 14:02

Hans Passant