golang调用dll,windows
冷知识
syscall包 并不会使用cgo,不用安装mingw-x64编译器, import "C"采用使用cgo
使用syscall.LoadLibrary(dllPath)函数加载dll,syscall.Syscall(...)函数调用具体的函数接口
func GoCallDll2(a, b int) uintptr {
dllFile, _ := syscall.LoadLibrary(dllFileName)
fmt.Println("+++++++syscall.LoadLibrary:", dllFile, "+++++++")
defer syscall.FreeLibrary(dllFile)
add, err := syscall.GetProcAddress(dllFile, "add")
fmt.Println("GetProcAddress", add)
ret, _, err := syscall.Syscall(add,
2,
IntPtr(a),
IntPtr(b),
0)
if err != nil && IsFinishError(err) {
fmt.Println(dllFileName+fmt.Sprintf(":%d+%d", a, b)+"运算结果为:", ret)
} else {
fmt.Println(fmt.Sprintf("%+v", err))
}
return ret
}
使用syscall.NewLazyDLL()加载dll,使用接口函数.Call(uintptr类型的参数)来调用函数
func GoCallDll1(a, b int) uintptr {
dllFile := syscall.NewLazyDLL(dllFileName)
fmt.Println("dll:", dllFile.Name)
add := dllFile.NewProc("add")
fmt.Println("+++++++NewProc:", add, "+++++++")
ret, _, err := add.Call(IntPtr(a), IntPtr(b))
if err != nil && IsFinishError(err) {
fmt.Println(dllFileName+fmt.Sprintf(":%d+%d", a, b)+"运算结果为:", ret)
} else {
fmt.Println(fmt.Sprintf("%+v", err))
}
return ret
}
使用syscall.MustLoadDLL(dllPath)加载dll,函数接口函数.Call(参数列表)调用
func GoCallDll3(a, b int) uintptr {
DllTestDef := syscall.MustLoadDLL(dllFileName)
add := DllTestDef.MustFindProc("add")
fmt.Println("+++++++MustFindProc:", add, "+++++++")
ret, _, err := add.Call(IntPtr(a), IntPtr(b))
if err != nil && IsFinishError(err) {
fmt.Println(dllFileName+fmt.Sprintf(":%d+%d", a, b)+"结果为:", ret)
} else {
fmt.Println(fmt.Sprintf("%+v", err))
}
return ret
}