1. go 生成动态库
- 必须添加import “C”
- 必须在要导出的函数前添加 //export+空格+函数名
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
}
生成dll命令
go build -ldflags "-s -w" -o main.dll -buildmode=c-shared main.go
-s 、-w 指令用于减小动态链接库的体积,-s是压缩,-w是去掉调试信息。-o可以指定生成文件的目录。
生成两个文件,main.dll 和main.h
2. 调用动态库
C调用dll
#include <stdio.h>
#include "Windows.h"
int main() {
//加载动态库到内存
HMODULE hdll = LoadLibrary("exportgo.dll");
typedef int (*SUMFUN)(int, int); // 定义函数指针类型
SUMFUN sum = (SUMFUN)GetProcAddress(hdll, "Sum");
int res = sum(3, 4);
printf("%d", res);
}
go调用dll
package main
import (
"fmt"
"syscall"
"unsafe"
)
func main() {
dll, _ := syscall.LoadDLL("exportgo.dll")
procSum, _ := dll.FindProc("Sum")
res, _, _ := procSum.Call(uintptr(3), uintptr(5))
fmt.Println(res)
}
func IntPtr(n int) uintptr {
return uintptr(n)
}
func StrPtr(s string) uintptr {
return uintptr(unsafe.Pointer(syscall.StringToUTF16Ptr(s)))
}