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:35:45 UTC 2019


On Thursday, 28 February 2019 at 03:33:25 UTC, Sam Johnson wrote:
> ```
> 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);
> }
> ```
>
> [...]

Ignore the `.clone()` call -- that wasn't supposed to be here -- 
I thought maybe string.clone() might exist but it turns out it 
does not.


More information about the Digitalmars-d-learn mailing list