最近一個項目須要用到Go調用C++的DLL類庫 這裏記錄一下坑函數
GetDllVersion 函數原型: unsigned int GetDllVersion(void); 獲取dll版本信息 返回值:DLL版本信息((unsigned int),高字節爲主版本信息,低字節爲子版本信息 ===================================================================== SetQianNiuPath 函數原型: int SetQianNiuPath(const char * Path, unsigned int PathLen); 設置千牛安裝路徑(DLL不保存路徑) 參數: Path,千牛安裝路徑(最長不要超過255個字符) PathLen,安裝你路徑長度 返回值:0 成功 -1 路徑存在問題 -2 路徑文件夾不存在 =====================================================================
package main import ( "fmt" "syscall" "unsafe" ) var ( multiQianniuLogin = syscall.NewLazyDLL("MultiQianniuLoginDll.dll") getDllVersion = multiQianniuLogin.NewProc("GetDllVersion") ) // 獲取字符串的長度指針 func lenPtr(s string) uintptr { return uintptr(len(s)) } // 獲取數字的指針 func intPtr(n int) uintptr { return uintptr(n) } // 獲取字符串的指針 func strPtr(s string) uintptr { return uintptr(unsafe.Pointer(syscall.StringBytePtr(s))) } func main() { var ret uintptr var err error ret, _, err = getDllVersion.Call() fmt.Printf("%d.%d\n", byte(ret), uint8(ret>>8)) fmt.Println(err) path := "C:\\Program Files (x86)\\AliWorkbench" _, _, err = setQianNiuPath.Call(strPtr(path), lenPtr(path)) fmt.Println(err) }
$ GOARCH=386 go run main.go 1.0 The operation completed successfully. SetQianNiuPath, C:\Program Files (x86)\AliWorkbench 35 SetQianNiuPath result 0 The operation completed successfully.
syscall.StringToUTF16Ptr
可是類庫只能讀取到一個字節 改爲 syscall.StringBytePtr
正常讀取