Is it possible to detect garbage collection on a custom struct?

Hi!

I am using an external library (LIB or DLL) to allocate and free memory that is not in the scope of the garbage collector, in the following example externalAlloc and externalFree. For better handling, I packed the memory pointer in a Julia struct.

struct myStruct
   ptr
   function myStruct()
      ptr = externalAlloc()
      return new(ptr)
   end
end

myInstance = myStruct()

The problem is, as soon as the user doesn’t interact with myInstance anymore and it get’s garbage collected, the allocated memory behind ptr is still in use (memory leak). So my favorite solution would be a “garbage collector notification dispatch” for myStruct, so that I can free the memory, like:

# this is called right before GC releases the memory for `myInstance`
function gcNotification(str::myStruct)
   externalFree(str.ptr)
   @info "Bye bye!"
end

Is there something like that out there? Or is there a better way to handle this process?

Thanks and best regards,
ThummeTo

You are looking for a finalizer: ?finalizer

3 Likes

Ah yes, exactly what I was looking for! Thank you!

(only thing is finalizer only works for mutable structs)

To conclude my example, the solution would be:

mutable struct myStruct
   ptr
   function myStruct()
      ptr = externalAlloc()
      inst = new(ptr)
      return finalizer(finalize!, inst)
   end
end

function finalize!(str::myStruct)
   externalFree(str.ptr)
end
2 Likes