1. 编写Go文件
import "C"
exec: "gcc": executable file not found in %PATH%
export不能省略,否则C#语言无法找到入口
package main
import "fmt"
import "C"
func main() {
}
//PrintHello :
//export PrintHello
func PrintHello() {
fmt.Println("Hello From Golang")
}
//Sum :
//export Sum
func Sum(a, b int) int {
return a + b
}
完成之后,使用go命令导出DLL文件
go build --buildmode=c-shared -o main.dll main.go
执行文件完成之后,会在目录下生成main.dll 和 main.h 文件。
2. 编写C#文件
using System;
using System.Runtime.InteropServices;
namespace CallGoDLL
{
class Program
{
[DllImport("main", EntryPoint = "PrintHello")]
extern static void PrintHello();
[DllImport("main", EntryPoint = "Sum")]
extern static int Sum(int a, int b);
static void Main(string[] args)
{
PrintHello();
int c = Sum(3, 5);
Console.WriteLine("Call Go Func to Add 3 and 5, result is " + c);
Console.ReadKey();
}
}
}
输出结果:
Hello From Golang
Call Go Func to Add 3 and 5, result is 8
需要注意:
System.BadImageFormatException:“试图加载格式不正确的程序。