dtqu72830 2017-06-10 17:05
浏览 190
已采纳

用cgo在C语言中编写go字符串

I'm trying to make a go string from C. I have the pointer and the length, so if I was doing it from go, I could call the C.GoStringN function.

cgo generates the GoString struct, so I was wondering if I could use it directly:

// struct generated by cgo
typedef struct { const char *p; GoInt n; } GoString;

// I have s and n from somewhere else, can I do this ?
const char* s = ... ; // I own this and dont want go to free it
int n = ... ;

GoString st = {s, n } ;

I'm using this in here to make a go string out of a char* whose lifetime I control. The GoString is then used as an argument to a go function:

//export Nbytes
func Nbytes(s string) int {
  ...
}

Will go's garbage collector attempt to reclaim the memory ?

  • 写回答

1条回答 默认 最新

  • duanlin1933 2017-06-11 04:18
    关注

    Go's garbage collector will not try to reclaim memory allocated using the C memory allocator. What you are describing should be safe. Of course, you may not be able to free the C memory, because you don't know when Go will be done with it.

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

报告相同问题?

悬赏问题

  • ¥15 安装svn网络有问题怎么办
  • ¥15 Python爬取指定微博话题下的内容,保存为txt
  • ¥15 vue2登录调用后端接口如何实现
  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥15 latex怎么处理论文引理引用参考文献