duanchandun1860 2018-05-22 09:49
浏览 108
已采纳

转到库中的C#| BadImageFormatException

I would like to create a library out of go-code and use it inside a C# winforms project.
For the error scroll to the bottom.

Setup

  • GO 1.10.2
  • tdm-gcc-5.1.0-3
  • Windows 10 / x64
  • Go-project called exprt

What I've tried

I've created a minimal go-tool that creates a file in the working-dir:

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);
}

The next steps were taken from Building a dll with Go 1.7.

I've then compiled to c-archive with the following command: go build -buildmode=c-archive which gives me exprt.a and exprt.h.

After that I've created a file called goDLL.c (1:1 as in the link above) and inserted this code:

#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() {
}

Lastly I've run this command to create my final dll:
gcc -shared -pthread -o goDLL.dll goDLL.c exprt.a -lWinMM -lntdll -lWS2_32 which gave me "goDLL.dll".

My problem

In C# I've created a winforms-project with 1 button that calls this declared function (copied the dll to the debug-folder):

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

Error

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

Sorry for that big block of text but this was the most minimal test I could think off.

I appreciate every help in here.

  • 写回答

1条回答 默认 最新

  • doushifen4060 2018-05-22 12:42
    关注

    Well, in the given answer here https://social.msdn.microsoft.com/Forums/vstudio/en-US/ee3df896-1d33-451b-a8a3-716294b44b2b/socket-programming-on-64bit-machine?forum=vclanguage there is written:

    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.

    So the build as described in my question is correct.

    Solution
    The C#-Project has to be explicitly set to x64. AnyCPU won't work and throw the error shown in the question above.

    Everything is working now. I'm leaving the question and answer as this is a full explanation of how to get go-code running out of C#.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 django项目运行报编码错误
  • ¥15 请问这个是什么意思?
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用
  • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。
  • ¥15 怎么配置广告联盟瀑布流
  • ¥15 Rstudio 保存代码闪退