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 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!