next | previous | forward | backward | up | top | index | toc | Macaulay2 website
ForeignFunctions :: registerFinalizer(ForeignObject,Function)

registerFinalizer(ForeignObject,Function) -- register a finalizer for a foreign object

Synopsis

Description

If a foreign pointer object corresponds to memory that was not allocated by the GC garbage collector, then a function to properly deallocate this memory when the Pointer object that stores this pointer is garbage collected should be called. The function should take a single argument, a foreign object, typically of type voidstar, which corresponds to the memory to deallocate.

i1 : malloc = foreignFunction("malloc", voidstar, ulong)

o1 = malloc

o1 : ForeignFunction
i2 : free = foreignFunction("free", void, voidstar)

o2 = free

o2 : ForeignFunction
i3 : finalizer = x -> (print("freeing memory at " | net x); free x)

o3 = finalizer

o3 : FunctionClosure
i4 : for i to 9 do (x := malloc 8; registerFinalizer(x, finalizer))
i5 : collectGarbage()
freeing memory at 0x7ffd0404f080
freeing memory at 0x7ffd0404f8a0freeing memory at 0x7ffd0404ff60
freeing memory at 0x7ffd0404f8c0
freeing memory at 0x7ffd0404f670
freeing memory at 0x7ffd04050070
freeing memory at 0x7ffd0404efe0
freeing memory at 0x7ffd0404fea0
freeing memory at 0x7ffd0404f5f0
freeing memory at 0x7ffd0404f8a0

Ways to use this method: