我正在将一个带有指向值的指针的 C 结构体传递给一个 Go 函数。

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

CGO I am passing a C struct with a pointer to a value to a go function,

问题

我对于以下情况是否需要清理内存感到困惑:

我有一个C函数,它创建一个C结构体并将其传递给一个Go函数。C结构体包含一个值数组(使用指针算术)。Go函数填充这个数组并返回。在调用的C函数中,我将值从C结构体中复制出来并不存储它们。

由于这是在Go中创建的,它会进行垃圾回收吗?

  1. /*
  2. C代码
  3. */
  4. int go_func(c_struct *s);
  5. struct c_struct{
  6. val *values;
  7. size_t *values_cnt;
  8. };
  9. void example_call()
  10. {
  11. struct c_struct s;
  12. go_func(&s);
  13. copy_values(s);
  14. }
  15. /*
  16. Go代码
  17. */
  18. func go_func(c *C.c_struct){
  19. var varr *C.val
  20. var v C.val = createValues()
  21. C.set_val_in_array(varr, *v, C.size_t(0))
  22. c.values = varr
  23. }

请注意,我只会翻译你提供的内容,不会回答关于翻译的问题。

英文:

I am confused as to if I need to cleanup the memory in the following scenario?

I have a C function that creates a C struct and passes it to a Go function. The C struct contains an array of values (using pointer arithmetic). The Go function populates this array and returns. In the calling C function I copy the values out of the C struct and do not store them.

As this is created in Go is this garbage collected?

  1. /*
  2. C code
  3. */
  4. int go_func(c_struct *s);
  5. struct c_struct{
  6. val *values;
  7. size_t *values_cnt;
  8. };
  9. void example_call()
  10. {
  11. struct c_struct s;
  12. go_func(&s)
  13. copy_values(s)
  14. }
  15. /*
  16. go code
  17. */
  18. func go_func(c *C.c_struct){
  19. var varr *C.val
  20. var v C.val = createValues()
  21. C.set_val_in_array(varr, *v, C.size_t(0))
  22. c.values = varr
  23. }

答案1

得分: 1

是的,在Go中,由于内存是在Go中创建的,它肯定会被垃圾回收。

英文:

Yes, it would definitely be garbage collected in Go as the memory is being created in Go.

huangapple
  • 本文由 发表于 2017年2月2日 18:46:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/42000145.html
匿名

发表评论

匿名网友

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

确定