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.