golang调用dll的接口三种方式

1.使用syscall.NewLazyDLL()加载dll,使用接口函数.Call(uintptr类型的参数)来调用函数

(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
}

2.使用syscall.MustLoadDLL(dllPath)加载dll,函数接口函数.Call(参数列表)调用

(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)
}

3.使用syscall.LoadLibrary(dllPath)函数加载dll,syscall.Syscall(...)函数调用具体的函数接口,如下:

(1)例如:调用获取数据接口函数

func get_ConnData()string{
    dllPath := "C:\\dll"
	handle, err := syscall.LoadLibrary(dllPath)
	if err != nil {
		fmt.Printf("Error: %s\n", err)
		return err
	}
	defer syscall.FreeLibrary(handle)

	export_conn, err := syscall.GetProcAddress(handle, "export_conn")
	if err != nil {
		fmt.Printf("Error: %s\n", err)
		return err
	}
	ret, _, _ := syscall.Syscall(export_conn, IntPtr("5"))
	if err != nil {
		fmt.Printf("Error: %s\n", 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)
}

  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值