参考博客:C# 调用 Golang 编写的动态链接库(DLL)
package main
import (
"unsafe"
)
/*
#include <stdlib.h>
*/
import "C"
//export Free
func Free(p *C.char){
C.free(unsafe.Pointer(p))
}
//export GetSayHellow
func GetSayHellow() *C.char{
return C.CString("hellow word")
}
func main() {
}
编译Dll
64位dll
go build -buildmode=c-shared -o test.dll .\test.go
32位dll
set GOARCH=386
set CGO_ENABLED=1
go build -buildmode=c-shared -o test.dll .\test.go
去掉调试信息-ldflags "-s -w"
go build -ldflags "-s -w" -buildmode=c-shared -o test.dll .\test.go
此时会生成test.dll
和 test.h
,可以看见到处函数
注意事项
- 导出函数
//export xxxx(函数名)
不可以省,否则不会导出函数 - 添加C code代码必须紧邻
import "C"
,如下
/*
c code,例如#include<stdio.h>
*/
import "C"