dseomy1964
2019-09-20 13:31
浏览 908
已采纳

golang从dll返回char *作为返回值

I'm using golang to call a Dll function like char* fn(), the dll is not written by myself and I cannot change it. Here's my code:

package main

import (
    "fmt"
    "syscall"
    "unsafe"
)

func main() {
    dll := syscall.MustLoadDLL("my.dll")
    fn := dll.MustFindProc("fn")

    r, _, _ := fn.Call()

    p := (*byte)(unsafe.Pointer(r))
    // define a slice to fill with the p string
    data := make([]byte, 0)

    // loop until find '\0'
    for *p != 0 {
        data = append(data, *p)        // append 1 byte
        r += unsafe.Sizeof(byte(0))    // move r to next byte
        p = (*byte)(unsafe.Pointer(r)) // get the byte value
    }
    name := string(data) // convert to Golang string
    fmt.Println(name)
}

I have some questions:

  1. Is there any better way of doing this? There're hundred of dll functions like this, I'll have to write the loop for all functions.
  2. For very-long-string like 100k+ bytes, will append() cause performance issue?
  3. Solved. the unsafe.Pointer(r) causes linter govet shows warning possible misuse of unsafe.Pointer, but the code runs fine, how to avoid this warning? Solution: This can be solved by adding -unsafeptr=false to govet command line, for vim-ale, add let g:ale_go_govet_options = '-unsafeptr=false'.

enter image description here

图片转代码服务由CSDN问答提供 功能建议

我正在使用golang调用诸如 char * fn()之类的Dll函数, dll不是我自己写的,我无法更改。 这是我的代码:

 程序包main 
 
import(
“ fmt” 
“ syscall” 
“ unsafe” 
)
 
func main()  {
 dll:= syscall.MustLoadDLL(“ my.dll”)
 fn:= dll.MustFindProc(“ fn”)
 
r,_,_:= fn.Call()
 
p:=  (* byte)(unsafe.Pointer(r))
 //定义要用p字符串填充的切片
 data:= make([] byte,0)
 
 //循环直到找到'\ 0  '
 for * p!= 0 {
 data = append(data,* p)//追加1个字节
r + =不安全Sizeof(byte(0))//将r移至下一个字节
p =(  * byte)(unsafe.Pointer(r))//获取字节值
} 
 name:= string(data)//转换为Golang字符串
 fmt.Println(name)
} 
   
 
 

我有一些问题:

  1. 是否有更好的方法? 有数百个这样的dll函数,我必须为所有函数编写循环。
  2. 对于非常长的字符串(如100k +字节),将 append()导致性能问题?
  3. 已解决 unsafe.Pointer(r)导致linter govet 显示警告 unsafe.Pointer 可能被误用,但是代码运行良好,如何避免这种情况 警告? 解决方案:这可以通过在 vim-ale govet 命令行中添加 -unsafeptr = false 来解决, 添加 let g:ale_go_govet_options ='-unsafeptr = false'

    ”在此处输入图片描述“

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

1条回答 默认 最新

相关推荐 更多相似问题