【发布时间】:2019-09-20 13:31:56
【问题描述】:
我正在使用golang调用像char* fn()这样的Dll函数,该dll不是我自己编写的,我无法更改它。这是我的代码:
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)
}
我有一些问题:
- 有没有更好的方法来做到这一点?这样的dll函数有上百个,我得为所有函数编写循环。
- 对于像 100k+ 字节这样的超长字符串,
append()会导致性能问题吗? -
已解决。
unsafe.Pointer(r)导致 linter govet 显示警告possible misuse of unsafe.Pointer,但代码运行良好,如何避免此警告? 解决方案: 这可以通过在govet命令行中添加-unsafeptr=false来解决,对于vim-ale,添加let g:ale_go_govet_options = '-unsafeptr=false'。
【问题讨论】:
-
为什么不直接使用
C.GoString? -
考虑添加您的解决方案作为答案
标签: go unsafe-pointers