Deleting memory in go

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

Deleting memory in go

问题

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

这是我的代码流程:

  1. func f_Go(){
  2. f_C(&buf);//c函数
  3. buff := C.GoBytes(unsafe.Pointer(buf), size) //在访问buf之后,我们必须删除buf以避免内存泄漏
  4. }
  5. void f_C(char *buf){
  6. f_C++(&buf);//c++函数
  7. }
  8. void f_C++(char **buf){ //在这里使用new来分配内存
  9. *buf = new[20];
  10. memcpy(*buf, "hhhhhhjdfkwejfkjkdj", 20);//将内容复制到*buf
  11. }

我能够在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 :

  1. func f_Go(){
  2. f_C(&buf);//c function
  3. buff := C.GoBytes(unsafe.Pointer(buf), size) //after accessing buf we have to delete buf for avoiding memory leak
  4. }
  5. void f_C(char *buf){
  6. f_C++(&buf);//c++ function
  7. }
  8. void f_C++(char **buf){ //here using new I am allocating memory
  9. *buf = new[20];
  10. memcpy(*buf, "hhhhhhjdfkwejfkjkdj", 20);//cpy content into *buf
  11. }

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++文件中可以这样做:

  1. extern "C" {
  2. void create_buf(char **buf) {
  3. *buf = new char[20];
  4. ...
  5. }
  6. void free_buf(char **buf) {
  7. delete[] *buf;
  8. *buf = nullptr;
  9. }
  10. }

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

英文:

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

  1. extern "C" {
  2. void create_buf(char **buf) {
  3. *buf = new char[20];
  4. ...
  5. }
  6. void free_buf(char **buf) {
  7. delete[] *buf;
  8. *buf = nullptr;
  9. }
  10. }

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:

确定