1. go 生成动态库
    - 必须添加import “C”
    - 必须在要导出的函数前添加 //export+空格+函数名

    1. package main
    2. import "C"
    3. import "fmt"
    4. //export PrintBye
    5. func PrintBye() {
    6. fmt.Println("From DLL: Bye!")
    7. }
    8. //export Sum
    9. func Sum(a int, b int) int {
    10. return a + b
    11. }
    12. func main() {
    13. // Need a main function to make CGO compile package as C shared library
    14. }

    生成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

    1. #include <stdio.h>
    2. #include "Windows.h"
    3. int main() {
    4. //加载动态库到内存
    5. HMODULE hdll = LoadLibrary("exportgo.dll");
    6. typedef int (*SUMFUN)(int, int); // 定义函数指针类型
    7. SUMFUN sum = (SUMFUN)GetProcAddress(hdll, "Sum");
    8. int res = sum(3, 4);
    9. printf("%d", res);
    10. }

    go调用dll

    1. package main
    2. import (
    3. "fmt"
    4. "syscall"
    5. "unsafe"
    6. )
    7. func main() {
    8. dll, _ := syscall.LoadDLL("exportgo.dll")
    9. procSum, _ := dll.FindProc("Sum")
    10. res, _, _ := procSum.Call(uintptr(3), uintptr(5))
    11. fmt.Println(res)
    12. }
    13. func IntPtr(n int) uintptr {
    14. return uintptr(n)
    15. }
    16. func StrPtr(s string) uintptr {
    17. return uintptr(unsafe.Pointer(syscall.StringToUTF16Ptr(s)))
    18. }