This is a creation in Article, where the information may have evolved or changed.
First write the Golang program Exportgo.go:
package mainimport "C"import "fmt"//export PrintByefunc PrintBye() { fmt.Println("From DLL: Bye!")}//export Sumfunc 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 DLL file:
go build -buildmode=c-shared -o exportgo.dll exportgo.go
Compiled to get Exportgo.dll and exportgo.h two files.
Refer to the function definition in the Exportgo.h file and compose 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.
>importgo.exeHello World!From DLL: Bye!55