转到 C# 库 | BadImageFormatException异常

Go to library to C# | BadImageFormatException

我想用 go-code 创建一个库并在 C# winforms 项目中使用它。
错误滚动到底部。

设置

我试过的

我创建了一个最小的 go-tool,它在工作目录中创建了一个文件:

package main

import (
    "os"
    "C"
)

func main() {
    // nothing here
}

//export Test
func Test() {
    os.OpenFile("created_file.txt", os.O_RDONLY|os.O_CREATE, 0666);
}

接下来的步骤取自

然后我用下面的命令编译成 c-archivego build -buildmode=c-archive 这给了我 exprt.aexprt.h.

之后,我创建了一个名为 goDLL.c 的文件(如上文 link 中的 1:1)并插入了以下代码:

#include <stdio.h>
#include "exprt.h"
// force gcc to link in go runtime (may be a better solution than this)
void dummy() {
    Test();
}
int main() {
}

最后我 运行 这个命令来创建我的最终 dll:
gcc -shared -pthread -o goDLL.dll goDLL.c exprt.a -lWinMM -lntdll -lWS2_32 这给了我 "goDLL.dll".

我的问题

在 C# 中,我创建了一个带有 1 个按钮的 winforms 项目,它调用这个声明的函数(将 dll 复制到调试文件夹):

[DllImport("goDLL.dll")]
private static extern void Test();

错误

System.BadImageFormatException: "An attempt was made to load a program with an incorrect format. (HRESULT: 0x8007000B)"

抱歉,那一大段文字,但这是我能想到的最简单的测试。

感谢这里的每一个帮助。

好吧,在此处给出的答案中 https://social.msdn.microsoft.com/Forums/vstudio/en-US/ee3df896-1d33-451b-a8a3-716294b44b2b/socket-programming-on-64bit-machine?forum=vclanguage 写着:

The implementation is in a file called ws2_32.dll and there are 32-bit and 64-bit versions of the DLL in 64-bit Windows.

所以我的问题中描述的构建是正确的。

解决方案
C#-Project 必须显式设置为 x64。 AnyCPU 将不起作用并抛出上述问题中显示的错误。

现在一切正常。我将留下问题和答案,因为这是对如何从 C# 中获取 go-code 运行 的完整解释。