how to pass a malloc'd C string over to be managed by the GC

Sam Johnson sam at durosoft.com
Thu Feb 28 03:33:25 UTC 2019


```
string snappyCompress(const string plaintext) {
	import deimos.snappy.snappy : snappy_compress, 
snappy_max_compressed_length, SNAPPY_OK;
	import core.stdc.stdlib : malloc, free;
	import std.string : fromStringz, toStringz;
	char *input = cast(char *) toStringz(plaintext);
	size_t output_length = 
snappy_max_compressed_length(plaintext.length);
	char *output = cast(char *) malloc(output_length);
	if(snappy_compress(input, plaintext.length, output, 
&output_length) == SNAPPY_OK) {
		string ret = (cast(string) fromStringz(output)).clone();
                 // <---- do something magical here
		return ret;
	}
	assert(0);
}
```

How can I get the GC to automatically garbage collect the 
`output` malloc call by tracking the returned `ret` reference? Or 
is this already managed by the gc because I cast to a `string`?


More information about the Digitalmars-d-learn mailing list