BadImageFormatException

Qwe*_*y01 3 c# c++

我正在将C++ Dlls调用到C#中并遇到了问题

C++函数:

    int _declspec(dllexport) CompressPacket(unsigned char *buff, int offset, int len);
Run Code Online (Sandbox Code Playgroud)

C#功能:

    [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;
    }
Run Code Online (Sandbox Code Playgroud)

什么时候

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

运行,我得到一个BadImageFormatException

由于C#编辑器是VSC#Express,它不能编译64位程序,所以我不确定这个问题任何想法都会很棒

Han*_*ant 11

Express版中缺少的Platform Target设置几乎肯定是您的问题.您必须手动编辑项目的.csproj文件.运行notepad.exe并打开.csproj文件.找到如下所示的属性组:

 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
Run Code Online (Sandbox Code Playgroud)

并添加此行:

    <PlatformTarget>x86</PlatformTarget>
Run Code Online (Sandbox Code Playgroud)

重复下面的Release配置组.

你的下一个问题是函数的名称,如果你用C++编译它就会被装饰.声明如下:

 extern "C" __declspec(dllexport) 
 int  __stdcall HuffCompress(unsigned char *buff, int offset, int len);
Run Code Online (Sandbox Code Playgroud)

并且您的C#声明是错误的,将ref关键字放在第一个参数上.