Go to library to 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.


  • 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 (

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() {
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):

private static extern void Test();


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.

asked on Stack Overflow May 22, 2018 by C4d • edited May 22, 2018 by C4d

1 Answer


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.

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#.

answered on Stack Overflow May 22, 2018 by C4d

User contributions licensed under CC BY-SA 3.0