Managing malloced memory
Steven Schveighoffer
schveiguy at gmail.com
Wed Oct 6 18:29:34 UTC 2021
On 10/6/21 2:06 PM, anon wrote:
> I interface to a C library that gives me a malloced object. How can I
> manage that pointer so that it gets freed automatically.
> What I've thought of so far:
> * scope(exit): not an option because I want to return that memory
> * struct wrapper: Doesn't work because if I pass it to another function,
> they also destroy it (sometimes). Also same problem as with scope(exit)
> * struct wrapped in automem/ refcounted: The struct still leaves
> original scope and calls the destructor
If the memory is the only resource it is consuming, you can use a
GC-allocated wrapper.
This is how I would do it:
```d
struct GCWrapped(T)
{
private T *_val;
this(T* val) { _val = val; }
ref T get() { return *_val; }
alias get this; // automatically unwrap
~this() { free(_val); _val = null; }
@disable this(this); // disable copying to avoid double-free
}
GCWrapped!T *wrap(T)(T *item) {
return new GCWrapped!T(item);
}
// usage
auto wrapped = wrap(cFunction());
// use wrapped wherever you need to access a T.
```
You can return this thing and pass it around, and the GC will keep it
alive until it's not needed. Then on collection, the value is freed.
If this contains a non-memory resource, such as a file or socket, then
those are much more limited, and you probably want to use deterministic
destruction instead.
-Steve
More information about the Digitalmars-d-learn
mailing list