Deleting memory in go

huangapple go评论103阅读模式
英文:

Deleting memory in go

问题

我正在使用new在C++中分配内存,然后在我的Go代码中访问它。
有没有办法在Go代码中删除这块内存。

这是我的代码流程:

func f_Go(){
    
    f_C(&buf);//c函数
    buff := C.GoBytes(unsafe.Pointer(buf), size) //在访问buf之后,我们必须删除buf以避免内存泄漏
}

void f_C(char *buf){

    f_C++(&buf);//c++函数
}

void f_C++(char **buf){ //在这里使用new来分配内存

*buf = new[20];
memcpy(*buf, "hhhhhhjdfkwejfkjkdj", 20);//将内容复制到*buf

}

我能够在Go中以这种方式访问buf,但之后我们必须删除这块内存。
所以我的问题是如何删除这块内存。

英文:

I am allocating memory in c++ using new which I am accessing in my go code.
Is there any way to delete this memory in go code.

This is the flow of my code :

func f_Go(){
    
    f_C(&buf);//c function
    buff := C.GoBytes(unsafe.Pointer(buf), size) //after accessing buf we have to delete buf for avoiding memory leak
}

void f_C(char *buf){

    f_C++(&buf);//c++ function
}

void f_C++(char **buf){ //here using new I am allocating memory

*buf = new[20];
memcpy(*buf, "hhhhhhjdfkwejfkjkdj", 20);//cpy content into *buf

}

using like this way I am able to access buf there in go but later we have to delete this memory.
So my question is what is the way to delete this memory.

答案1

得分: 2

你可以导出一个执行释放内存的第二个函数。在你的C++文件中可以这样做:

extern "C" {
    void create_buf(char **buf) {
        *buf = new char[20];
        ...
    }

    void free_buf(char **buf) {
        delete[] *buf;
        *buf = nullptr;
    }
}

现在你有另一个可以使用CGo调用的函数来进行清理。

英文:

You can export a second function that performs the deallocation. Something like this should do in your C++ file:

extern "C" {
    void create_buf(char **buf) {
        *buf = new char[20];
        ...
    }

    void free_buf(char **buf) {
        delete[] *buf;
        *buf = nullptr;
    }
}

Now you have another function you can call using CGo to perform the clean up.

huangapple
  • 本文由 发表于 2014年11月20日 18:00:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/27036670.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定