七叶笔记 » golang编程 » Go语言调用Windows动态库的两种方法

Go语言调用Windows动态库的两种方法

Go语言调用动态库需要注意动态库的版本,比如调用32位的动态库必须使用32位的go,否则会报下面的错误(xxx.dll是动态库的名称):

panic: Failed to load xxx.dll: %1 is not a valid Win32 application.

  1. 使用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") 
} 

相关文章