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

ThummeTo
Thu, 04 Jan 2024 12:34:26 +0000
General Usage

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

3 posts - 2 participants