Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Free C pointer when collected by GC

Tags:

go

I have a package that interfaces with a C library. Now I need to store a pointer to a C struct in the Go struct

type A struct {
  s *C.struct_b
}

Obviously this pointer needs to be freed before the struct is collected by the GC. How can I accomplish that?


1 Answers

The best thing to do is when possible copy the C struct into go controlled memory.

var ns C.struct_b
ns = *A.s
A.s = &ns

Obviously, that won't work in all cases. C.struct_b may be too complicated or shared with something still in C code. In this case, you need to create a .Free() or .Close() method (whichever makes more sense) and document that the user of your struct must call it. In Go, a Free method should always be safe to call. For example, after free is run, be sure to set A.s = nil so that if the user calls Free twice, the program does not crash.

There is also a way to create finalizers. See another answer I wrote here. However, they may not always run and if garbage is created fast enough, it is very possible that the creation of garbage will out pace collection. This should be considered as a supplement to having a Free/Close method and not a replacement.

like image 159
Stephen Weinberg Avatar answered Feb 28 '26 20:02

Stephen Weinberg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!