3 ms·
Would a PointerScope pattern work well here? Functions that need to return dynamically sized things take a *PointerScope parameter, which is a struct with two
by jacobn 4y ago
Would a PointerScope pattern work well here?
Functions that need to return dynamically sized things take a *PointerScope parameter, which is a struct with two function pointers: malloc() and close().
The api function uses the provided malloc, the caller calls close when they’re done with the returned data.
This can then be used with a bunch of calls (and by the caller itself), and then at the end all the allocations get freed with one simple call.
Obviously the PointerScope would internally need to keep track of what was allocated, so it’s a far from simple struct&code combo, but should provide decent user ergonomics?
Add a create() function too, to create a new PointerScope and you have an entire malloc/free replacing resource management paradigm! ;)