如何释放在参数中使用的C变量

huangapple go评论74阅读模式
英文:

How to free C variables used in parameters

问题

根据你提供的内容,以下是翻译好的部分:

https://golang.org/cmd/cgo/ 上写道:

// C 字符串是在 C 堆上使用 malloc 分配的。
// 调用者有责任安排它被释放,比如通过调用 C.free(如果需要,请确保包含 stdlib.h)。

如果我在参数中内联使用 C.CString,我仍然需要调用 free() 吗?在这种情况下,最佳实践是什么?

示例:

ret := C.RandomCFunction(C.CString("foo"))
英文:

https://golang.org/cmd/cgo/ says:

// The C string is allocated in the C heap using malloc.
// It is the caller's responsibility to arrange for it to be
// freed, such as by calling C.free (be sure to include stdlib.h
// if C.free is needed).

What if I use C.CString inline as parameter? I would have to free() it anyways, right? What is best practise in this case?

Example:

ret := C.RandomCFunction(C.CString("foo"))

答案1

得分: 1

如果将其作为内联参数使用,你只能在函数内部释放它。虽然你可以这样做,但这是一个非常糟糕的做法。如果你在其他地方使用这个函数,并且计划稍后使用一个变量,它将意外地释放该变量。

只需将字符串移到函数调用前面作为一个变量,调用函数,然后释放它。

英文:

If you use it as inline parameter, you can only free it inside the function. While you could do that, it's a really bad practice. If you use this function elsewhere with a variable that you plan on using later, it will free the variable unintentionally.

Just move the string in front of the function call as a variable, call the function and then free it.

huangapple
  • 本文由 发表于 2017年2月1日 17:57:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/41976730.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定