首页 > 解决方案 > 转到库到 C# | 坏图像格式异常

问题描述

我想用 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);
}

接下来的步骤取自使用 Go 1.7 构建 dll

c-archive然后,我使用以下命令编译为:go build -buildmode=c-archive这给了我exprt.aexprt.h.

之后,我创建了一个名为goDLL.c(如上面链接中的 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)"

对不起,那一大块文字,但这是我能想到的最小的测试。

我感谢这里的每一个帮助。

标签: c#gocompilationshared-librariesshared

解决方案


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

该实现位于名为 ws2_32.dll 的文件中,在 64 位 Windows 中存在 32 位和 64 位版本的 DLL。

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

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

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


推荐阅读