golang怎么编译、调用dll文件
编译
exportgo.go
package main import "C" /* export PrintBye 的意思是将PrintBye方法通过PrintBye名暴露出去 */ //export PrintBye func PrintBye() { /* 这里是只能用println 不能用:log.Println()和fmt.Println() */ println("From DLL: Bye!") } //export Sum func Sum(a C.int, b C.int) C.int { return a b } //export Sub func Sub(a C.int, b C.int) C.int { return a - b } //export Hello func Hello(a C.int, b C.int) C.int { return a * b } func main() { // Need a main function to make CGO compile package as C shared library }
编译
>go build -buildmode=c-shared -o exportgo.dll exportgo.go
编译完成后,生成exportgo.dll和exportgo.h
调用
Called.go
package main import "C" import ( "log" "syscall" ) func main() { log.SetFlags(log.LstdFlags | log.Lshortfile) F4(50,30) F5(50,30) F6() } func F4(int1, int2 int) { log.Println(int1, int2) //引入dll文件方法1 dll := syscall.MustLoadDLL("exportgo.dll") //使用完后要释放 defer dll.Release() //调用dll的方法Sum proc := dll.MustFindProc("Sum") //使用sum函数,传递参数int1和int2 call, u, err := proc.Call(uintptr(int1), uintptr(int2)) //输出结果call log.Println(call) log.Println(u) log.Println(err) } func F5(int1, int2 int) { //引入dll文件方法2 dll := syscall.NewLazyDLL("exportgo.dll") //调用dll的方法Sub proc := dll.NewProc("Sub") //使用Sub函数,传递参数int1和int2 r, err, msg := proc.Call(uintptr(int1), uintptr(int2)) //输出结果r log.Println(r) log.Println(err) log.Println(msg) } func F6() { //引入dll文件 dll := syscall.NewLazyDLL("exportgo.dll") //调用dll的方法PrintBye proc := dll.NewProc("PrintBye") //调用dll的方法,不传递任何值 r, err, msg := proc.Call() //输出结果r log.Println(r) log.Println(err) log.Println(msg) }
执行结果
2022/03/26 14:48:00 Called.go:16: 50 30 2022/03/26 14:48:00 Called.go:26: 80 2022/03/26 14:48:00 Called.go:27: 8791506616320 2022/03/26 14:48:00 Called.go:28: The operation completed successfully. 2022/03/26 14:48:00 Called.go:38: 20 2022/03/26 14:48:00 Called.go:39: 8791503994880 2022/03/26 14:48:00 Called.go:40: The operation completed successfully. From DLL: Bye! 2022/03/26 14:48:00 Called.go:50: 0 2022/03/26 14:48:00 Called.go:51: 8791503994880 2022/03/26 14:48:00 Called.go:52: The operation completed successfully.
赞 (0)