最近有个客户需要使用go语言调用我们的dll库,于是写了个示例程序支持客户
package main
import "C"
import (
"fmt"
"syscall"
"unsafe"
)
func IntPtr(n int) uintptr {
return uintptr(n)
}
func StrPtr(s string) uintptr {
return uintptr(unsafe.Pointer(syscall.StringToUTF16Ptr(s)))
}
func Lib_initChinalinEncrypt() {
lib := syscall.NewLazyDLL("OrderEncrypt_x64.dll")
fmt.Println("dll:", lib.Name)
initChinalinEncrypt := lib.NewProc("initChinalinEncrypt")
fmt.Println("+++++++initChinalinEncrypt Proc:", initChinalinEncrypt, "Hellow")
ret, _, err := initChinalinEncrypt.Call()
if err != nil {
fmt.Println("lib.dll initChinalinEncrypt 运算结果为:", ret)
}
}
func Lib_authorize() {
lib := syscall.NewLazyDLL("OrderEncrypt_x64.dll")
fmt.Println("dll:", lib.Name)
authorize := lib.NewProc("authorize")
fmt.Println("+++++++authorize Proc:", authorize, "Hellow")
user_name := C.CString("username1")
username := uintptr(unsafe.Pointer((&user_name)))
pass_word := C.CString("password")
password := uintptr(unsafe.Pointer((&pass_word)))
ret, _, err := authorize.Call(username, uintptr(uint64(len("username"))),password,uintptr(uint64(len("password"))))
if err != nil {
fmt.Println("OrderEncrypt_x64.dll authorize 运算结果为:", ret)
}
}
func Lib_encryptFile() {
lib := syscall.NewLazyDLL("OrderEncrypt_x64.dll")
fmt.Println("dll:", lib.Name)
encryptFile := lib.NewProc("encryptFile")
fmt.Println("+++++++encryptFile Proc:", encryptFile, "Hellow")
src_File := C.CString("D:\\a\\ordersgo.txt")
srcFile := uintptr(unsafe.Pointer((&src_File)))
dst_File := C.CString("D:\\a\\out_ordersgo.txt")
dstFile := uintptr(unsafe.Pointer((&dst_File)))
ret, _, err := encryptFile.Call(srcFile, uintptr(uint64(len("srcFile"))),dstFile,uintptr(uint64(len("dstFile"))))
if err != nil {
fmt.Println("OrderEncrypt_x64.dll encryptFile 运算结果为:", ret)
}
}
func main() {
Lib_initChinalinEncrypt()
Lib_authorize()
fmt.Println("Hellow")
}
cgo传参对照表
注意的是golang由于数据类型和c++的不一致,在需要传参的时候需要把所有的参数都转换成uintptr指针类型,而且转换的过程需要借助unsafe.Pointer指针