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

How to free C variables used in parameters

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 inline 作为参数呢?无论如何我都必须free(),对吧?这种情况下的最佳做法是什么?

示例:

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

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

把函数调用前的字符串作为变量移动,调用函数然后释放即可