我如何/何时释放Go代码创建的C字符串的内存?

时间:2017-11-09 05:56:07

标签: go cgo

这是我的代码:

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)

}

当我执行代码时,我得到:

的Oc

它实际上是随机的。我似乎每次都有不同的东西。

可能是我从HelloWorld()方法传递 char数组

我错过了什么?

更新

当我删除时:

C.free(unsafe.Pointer(cs))

我得到了好的字符串。而不是随机字符。

但我需要C.free来释放记忆。这里建议:https://blog.golang.org/c-go-cgo

  

对C.CString的调用返回指向char开头的指针   数组,所以在函数退出之前我们将它转​​换为unsafe.Pointer   并使用C.free。

释放内存分配

我不确定该怎么做。

1 个答案:

答案 0 :(得分:2)

链接的示例释放已分配的内存,因为没有其他代码需要它。

如果你的Go函数需要返回一些已分配的内存以便它可以被某些C代码使用,那么Go函数不应该调用C.free,而是使用该内存的C代码应该负责在它之后释放它不再需要它了。

任意例子:

cgo/test/issue20910.go

cgo/test/issue20910.c