drq61040 2018-03-23 16:03
浏览 26
已采纳

访问字符串的原始字节

I'm trying to call a C function that expects a C string (char*) from go. I know about the C.CString function documented in the cgo documentation but as the function I'm calling will already make a copy, I'm trying to avoid the one Cstring makes.

Right now, I'm doing this, s being a go string

 var cs *C.char = (*C.char)( unsafe.Pointer(& []byte(s) [0]))

But I get the feeling that the []bytes(s) is making its own copy. Is it possible to just get the char* ?

  • 写回答

1条回答 默认 最新

  • dsvtnz6350 2018-03-23 16:25
    关注

    If you're doing this enough times that performance is a concern, it would really be advisable to keep the data in a slice to begin with.

    If you really want to access to the address of the string, you can use the unsafe package to convert it into a struct matching the string header. Using the reflect.StringHeader type:

    p := unsafe.Pointer((*(*reflect.StringHeader)(unsafe.Pointer(&s))).Data)
    

    Or using a slice as a proxy, since they both put the data pointer and length integers in the same field locations

    p := unsafe.Pointer(&(*(*[]byte)(unsafe.Pointer(&s)))[0])
    

    Or because the data pointer is first, you could use a uintptr alone

    p := unsafe.Pointer(*(*uintptr)(unsafe.Pointer(&s)))
    

    https://play.golang.org/p/ps1Py7Ax6QK

    None of these ways are guaranteed to work in all cases, or in future versions of Go, and none of the options are going to guarantee a null terminated string.

    The best, supported option is to create a shim in the cgo preamble to accept the go string, and convert it to a *char. CGO provides access to the following function to do this:

    const char *_GoStringPtr(_GoString_ s);
    

    See the Go references to C section in the documentation.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里