1. 編寫Go文件
注意,import "C"
需要系統中安裝gcc,否則會報錯:
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
需要注意:
DLL放在對應的文件夾下,目前是放置在Debug目錄下。
-
之前測試,一直會報錯
System.BadImageFormatException:“試圖加載格式不正確的程序。
后來猜測原因可能是導出的DLL版本不對,如果GCC是64位的,最后生成的DLL也會是64位的。
image.png
將目標平臺強制設置成x64位即可。