Free C pointer when collecting GC

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

type A struct {
  s *C.struct_b
}

      

Obviously, this pointer must be freed before the structure is collected by the GC. How can i do this?

+3


source to share


1 answer


It is best done when it is possible to copy the C structure to managed memory.

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

      



Obviously this will not work in all cases. C.struct_b might be overly complex or spread with something else in C code. In this case, you need to create a .Free () or .Close () method (whichever makes more sense) and a document to be named by the user of your structure. In Go, a free method must always be call-safe. For example, after starting the free run, make sure to set As = 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 start, and if the garbage is generated fast enough, it is very possible that the garbage creation will cause the tempo to be collected. This should be seen as an addition to the Free / Closed method and not a replacement.

+6


source







All Articles