问题描述
以下是我的代码:
helloworld.go :
package main
/ *
#include
* /
导入C
导入不安全
//导出HelloWorld
func HelloWorld()* C.char {
cs:= C.CString(Hello World!)
C.free(unsafe.Pointer(cs))
return cs
}
func main(){}
node-helloworld.cc :
#includehelloworld.h
#include< node.h>
#include< string>
命名空间演示{
使用v8 :: FunctionCallbackInfo;
使用v8 :: Isolate;
使用v8 :: Local;
使用v8 :: Object;
使用v8 :: String;
使用v8 :: Value;
方法(const FunctionCallbackInfo<值>& args){
隔离* 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)
}
当我执行我得到的代码时:
Oc
或 p>
#
或
etc
它实际上是随机的。我似乎每次都会得到不同的东西。
可能是我从 HelloWorld传递了 char array )方法。
我缺少什么?
UPDATE
当我删除时:
C.free unsafe.Pointer(cs))
我收到了很好的字符串。而不是随机的字符。
但我需要 C.free 来释放内存。这里推荐:
我不确定如何这样做。
链接的例子释放分配的内存,因为没有其他代码需要它。
如果你的Go函数需要返回一些分配的内存以便它可以被一些C代码使用,那么Go函数不应该调用C.free,而是使用该内存的C代码应该负责任何例子:
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
I am unsure how to do this.
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:
这篇关于如何/何时释放由Go代码创建的C字符串的内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!