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

时间:2017-02-01 09:57:43

标签: go cgo

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

// 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).

如果我使用C.CString内联作为参数怎么办?不管怎样我还是要free(),对吧?在这种情况下,最佳做法是什么?

示例:

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

1 个答案:

答案 0 :(得分:1)

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

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