Calling Go Function from C# – Code Review

I am trying to call golang dll from c#, and comparing results and performance against calling c dll from c#, so i did below:

I started with creating c dll and calling it
Step 1: Writing the c code

// cmdll.c
// Compile with: -LD
int __declspec(dllexport) SampleMethod(int i)
{
  return i*10;
}

Step 2: Compiling the C Code:

  • open Visual Studio x64 Native Tools Command Prompt
  • run command: cl -LD cmdll.c

Step 3: Writing the C# Code

// cm.cs
using System;
using System.Runtime.InteropServices;
public class MainClass
{
    [DllImport("Cmdll.dll")]
    public static extern int SampleMethod(int x); // function signature, must have a return type

    static void Main()
    {
        Console.WriteLine("SampleMethod() returns {0}.", SamplMethod(5));
    }
}

Step 4: Compile the C# file and build the exe as:

  • open Visual Studio x64 Native Tools Command Prompt
  • run command: csc -platform:x64 cm.cs

above things run smoothly

I wanted to do the same using golang, and followed below:

Step 1: Write Go Code:

//lib.go
package main

import "C"

//export SamplMethod
func SamplMethod(i int) int {
	return i * 10
}

func main() {
	// Need a main function to make CGO compile package as C shared library
}

Step 2: Create a dll file by compiling the above code as follows:

go build -ldflags="-s -w" -o lib.dll -buildmode=c-shared lib.go

i used -ldflags="-s -w" to reduce the resulting file size, and not sure what -buildmode Will I use, so randomly chosen c-shared Instead c-archive
UPDATE: I tried this as well go build -ldflags="-s -w" -o lib.dll -buildmode=c-archive lib.go and got the same result

Step 3: Write the AC code that does the combination .dll And .h file generated from go to generate an equivalent c dll

//goDll.c
#include <stdio.h>
#include "lib.h"
// force gcc to link in go runtime (may be a better solution than this)
GoInt SamplMethod(GoInt i);

void main() {
}

Step 4: Compile the goDll.c file as:

gcc -shared -pthread -o goDll.dll goDll.c lib.dll -lWinMM -lntdll -lWS2_32

Step 5: Build C# code to call the generated DLL, same code as above, but changing the DLL file name:

// cm.cs
using System;
using System.Runtime.InteropServices;
public class MainClass
{
    [DllImport("goDll.dll")]
    public static extern int SampleMethod(int x); // function signature, must have a return type

    static void Main()
    {
        Console.WriteLine("SampleMethod() returns {0}.", SamplMethod(5));
    }
}

Step 4: Compile the C# file and build the exe as:

  • open Visual Studio x64 Native Tools Command Prompt
  • run command: csc -platform:x64 cm.cs

then tried to run generate ./cm.exe file, but got the error below:

Unhandled Exception: System.EntryPointNotFoundException: Unable to find an entry point named 'SampleMethod' in DLL 'goDll.dll'.
   at MainClass.SampleMethod(Int32 i)
   at MainClass.Main()

Leave a Comment