文章目录
目录
- 1.使用syscall.NewLazyDLL()加载dll,使用接口函数.Call(uintptr类型的参数)来调用函数
- 2.使用syscall.MustLoadDLL(dllPath)加载dll,函数接口函数.Call(参数列表)调用
- 3.使用syscall.LoadLibrary(dllPath)函数加载dll,syscall.Syscall(…)函数调用具体的函数接口,如下:
(1)例如:调用初始化接口函数进行初始化操作
dllpath:="test.dll"
handle:=syscall.NewLazyDLL(dllpath)
//引号中的init即为dll中的函数方法
init:=handle.NewProc("init")
init.Call(BytePtr("C:\dll"))
(2)将string类型转换为uintptr类型的函数如下
func BytePtr(str string)uintptr{
s:=[]byte(str)
return uintptr(unsafe.Pointer(&s[0]))
}
(3)可将调用初始化接口后得到的handle返回,后续调用该dll中其他接口方法时就可直接使用handle.NewProc("接口方法名"),具体如下
func call_Init()*syscall.LazyDLL{
dllpath:="test.dll"
handle:=syscall.NewLazyDLL(dllpath)
//引号中的init即为dll中的函数方法
init:=handle.NewProc("init")
init.Call(BytePtr("C:\dll"))
return handle
}
(1)例如:调用callByReference接口函数
func Call_PassByValue(n int) error {
dllPath := "E:\Code\vs2015_project\demo\x64\Release\c2plusdll.dll"
handle := syscall.MustLoadDLL(dllPath)
callByReference := handle.MustFindProc("callByReference")
ret, _, err := callByReference.Call(IntPtr(n))
if err != nil {
fmt.Println("DllTestDef的运算结果为:", ret)
}
return nil
}
(2)将int类型转换为uintptr类型的函数如下:
func IntPtr(n int)uintptr{
return uintptr(n)
}
(1)例如:调用获取数据接口函数
func get_ConnData()string{
dllPath := "C:\dll"
handle, err := syscall.LoadLibrary(dllPath)
if err != nil {
fmt.Printf("Error: %sn", err)
return err
}
defer syscall.FreeLibrary(handle)
export_conn, err := syscall.GetProcAddress(handle, "export_conn")
if err != nil {
fmt.Printf("Error: %sn", err)
return err
}
ret, _, _ := syscall.Syscall(export_conn, IntPtr("5"))
if err != nil {
fmt.Printf("Error: %sn", err)
}
return uintptrTostr(ret)
}
(2)其中uintptrTostr函数为
func uintptrTostr(ptr uintptr)string{
p:=(*byte)(unsafe.Pointer(ptr))
data:=make([]byte,0)
for *p!=0{
data=append(data,*p)
ptr+=unsafe.Sizeof(byte(0))
p=(*byte)(unsafe.Pointer(ptr))
}
return string(data)
}
到此这篇关于golang调用dll的接口三种方式小结的文章就介绍到这了,更多相关golang调用dll接口内容请搜索风君子博客以前的文章或继续浏览下面的相关文章希望大家以后多多支持风君子博客!
您可能感兴趣的文章:
- golang调用c实现的dll接口细节分享