Golang needs gcc to compile the dll, so install MinGW first.
Windows 64-bit systems should download the 64-bit version of MinGW: https://sourceforge.net/projects/mingw-w64/
After downloading, run mingw-w64-install.exe to complete the MingGW installation.
Write the golang program exportgo.go:
package main
import "C"
import "fmt"
//export PrintBye
func PrintBye() {
fmt.Println("From DLL: Bye!")
}
//export Sum
func Sum(a int, b int) int {
return a + b;
}
func main() {
// Need a main function to make CGO compile package as C shared library
}
Compile into a DLL file:
go build -buildmode=c-shared -o exportgo.dll exportgo.go
After compiling, exportgo.dll and exportgo.h are obtained.
Referring to the function definitions in the exportgo.h file, write the C# file importgo.cs:
using System;
using System.Runtime.InteropServices;
namespace HelloWorld
{
class Hello
{
[DllImport("exportgo.dll", EntryPoint="PrintBye")]
static extern void PrintBye();
[DllImport("exportgo.dll", EntryPoint="Sum")]
static extern int Sum(int a, int b);
static void Main()
{
Console.WriteLine("Hello World!");
PrintBye();
Console.WriteLine(Sum(33, 22));
}
}
}
Compile CS file to get exe
csc importgo.cs
Put the exe and dll in the same directory and run it.
>importgo.exe
Hello World!
From DLL: Bye!
55
Replenish:
String parameters in golang can be referenced in C# as follows:
public struct GoString
{
public string Value { get; set; }
public int Length { get; set; }
public static implicit operator GoString(string s)
{
return new GoString() { Value = s, Length = s.Length };
}
public static implicit operator string(GoString s) => s.Value;
}