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.

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

报告相同问题?

悬赏问题

  • ¥30 YOLO检测微调结果p为1
  • ¥20 求快手直播间榜单匿名采集ID用户名简单能学会的
  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题