I'll answer both the generic question and the specific example.
JNA doesn't maintain any references to the native memory unless you allocate it yourself in JNA (e.g., define a byte[]
array or Memory
buffer that you pass to a function). In these cases, the native memory is freed when the Java object is garbage collected.
If you're not passing any memory to C to fill, JNA isn't going to do anything with the native memory, and you'd have to read the API documentation to see what your responsibility is for freeing the native string.
The C++ CString type isn't necessarily required to be freed unless it is stored in a new object. However, Go does implement the CString
as an object, and documents these requirements. For your particular example, the docs say:
Memory allocations made by C code are not known to Go's memory
manager. When you create a C string with C.CString (or any C memory
allocation) you must remember to free the memory when you're done with
it by calling C.free.
and from the cgo wiki:
One important thing to remember is that C.CString() will allocate a
new string of the appropriate length, and return it. That means the C
string is not going to be garbage collected and it is up to you to
free it. A standard way to do this follows.
// #include <stdlib.h>
import "C"
import "unsafe"
...
var cmsg *C.char = C.CString("hi")
defer C.free(unsafe.Pointer(cmsg))
// do something with the C string
Of course, you aren't required to use defer to call C.free(). You can
free the C string whenever you like, but it is your responsibility to
make sure it happens.