Go語言調用動態庫需要注意動態庫的版本,比如調用32位的動態庫必須使用32位的go,否則會報下面的錯誤(xxx.dll是動態庫的名稱):
panic: Failed to load xxx.dll: %1 is not a valid Win32 application.
-
使用syscall的NewLazyDLL和NewProc(效果如下)
2.使用syscall的LoadLibrary和GetProcAddress(效果如下)
3詳細代碼如下(zip.dll是一個提供壓縮解壓縮功能的第三方動態庫,kernel32.dll是Windows的系統庫):
packagemain
import (
"fmt"
"syscall"
)
func main() {
CompressFile()
fmt.Println("\n")
GetWindowVersion()
}
func CompressFile() {
Compress := syscall.NewLazyDLL("zip.dll")
Comp := Compress.NewProc("CompressFile")
ret, _, err := Comp.Call()
if ret != 1 {
fmt.Println("Compress result:壓縮失敗", err)
return
}
fmt.Println("Compress result:壓縮成功")
}
func GetWindowVersion() {
kernel , err := syscall.LoadLibrary("kernel32.dll")
if err != nil {
abort("LoadLibrary", err)
}
defer syscall.FreeLibrary(kernel)
proc, err := syscall.GetProcAddress(kernel, "GetVersion")
if err != nil {
abort("GetProcAddress", err)
}
ret, _, _ := syscall.Syscall(uintptr(proc), 0, 0, 0, 0)
print_version(uint32(ret))
}
func abort(funcname string, err error) {
panic(funcname + " failed: " + err.Error())
}
func print_version(v uint32) {
major := byte(v)
minor := uint8(v >> 8)
build := uint16(v >> 16)
print("windows version ", major, ".", minor, " (Build ", build, ")\n")
}
文章來源:智雲一二三科技
文章標題:Go語言調用Windows動態庫的兩種方法
文章地址:https://www.zhihuclub.com/88944.shtml