1. 首先撰写 golang 程序 testdll.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
}
   

2. 编译成 DLL 文件:

go build -buildmode=c-shared -o testdll.dll testdll.go

 

如果要编译.so , buildmode=shared

编译后得到 testdll.dll 和 testdll.h 两个文件。

3. c#中调用该DLL

using System.Runtime.InteropServices; 

[DllImport("testdll.dll")]
static extern int Sum(int a, int b);

int c = Sum(1, 2); 
Console.WriteLine($"Extern Sum: {c}"); 
Console.ReadLine();