4 ms·
In GC languages a common approach is to have "finalizers" to make something like this a possible and sometimes convenient way of dealing with a foreign API, I w
by Jach 4y ago
In GC languages a common approach is to have "finalizers" to make something like this a possible and sometimes convenient way of dealing with a foreign API, I wonder if what you saw was something similar? The idea is to allocate the foreign memory, then make a finalizer which is just a hook that will (eventually) call the foreign free only when some object (like a wrapper for the foreign memory) is collected. Something similar could be hidden behind some preprocessor macros, with guarantees only until the next OUR_MALLOC...
The problems for the GC languages tend to be fewer but if the wrapper is out of scope but someone grabbed and maintains a hold on the foreign memory directly, they're playing with fire as for when the GC will execute the finalizer hook and make that memory invalid. It's also a frustrating technique when foreign APIs -- particularly in certain graphics contexts -- require allocation threads to be the same as freeing threads, and of course depending on the implementation of free and the GC it might be an expensive operation to have a bunch of them suddenly happen at once when all you were expecting was a new native object and not a bunch of GC work behind the scenes.
- smarks 4y agoDefinitely not GC. This was K&R C on BSD Unix around 1984.
- pjmlp 4y agoThat is why finalizers are yesterday solution, most modern GC based languages have eventually catched up with Common Lisp and offer region based resource management (try-with-resources, use, using, defer, with,...), and in some cases trailing lambdas, which completly hide the resource management from the consumer. For scenarios like you're describing, .NET has SafeHandles for example.