问题
Here is my code:
helloworld.go:
package main
/*
#include <stdlib.h>
*/
import "C"
import "unsafe"
//export HelloWorld
func HelloWorld() *C.char {
cs := C.CString("Hello World!")
C.free(unsafe.Pointer(cs))
return cs
}
func main() {}
node-helloworld.cc:
#include "helloworld.h"
#include <node.h>
#include <string>
namespace demo {
using v8::FunctionCallbackInfo;
using v8::Isolate;
using v8::Local;
using v8::Object;
using v8::String;
using v8::Value;
void Method(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = args.GetIsolate();
args.GetReturnValue().Set(String::NewFromUtf8(isolate, HelloWorld()));
}
void init(Local<Object> exports) {
NODE_SET_METHOD(exports, "hello", Method);
}
NODE_MODULE(helloworld, init)
}
When I execute the code I get:
�Oc
or
��#
or
���
etc
It's actually random. I seem to be getting something different every time.
It might be that I am passing char array from HelloWorld()
method.
What am I missing?
UPDATE
When I remove:
C.free(unsafe.Pointer(cs))
I get the good string. And not random characters.
But I need C.free
to free the memory. It is recommended here: https://blog.golang.org/c-go-cgo
The call to C.CString returns a pointer to the start of the char array, so before the function exits we convert it to an unsafe.Pointer and release the memory allocation with C.free.
I am unsure how to do this.
回答1:
The linked example frees the allocated memory because no other code needs it.
If your Go function needs to return some allocated memory so that it can be used by some C code then the Go function should not call C.free, instead the C code that uses that memory should be responsible for freeing it after it does not need it anymore.
Arbitrary example:
cgo/test/issue20910.go
cgo/test/issue20910.c
来源:https://stackoverflow.com/questions/47194827/how-when-do-i-free-the-memory-of-a-c-string-created-by-go-code