I'm writing an interface to a C library. A C function allocates some memory, reads a value, and returns a void *
pointer to that buffer, to be subsequently freed.
I wish to be sure that when I assign the output of a call to nativecast(Str, $data)
to a Raku Str variable, the data is assigned to the variable (copied into), not just bound to it, so I can free the space allocated by the C function soon after the assignment.
This is approximately what the code looks like:
my Pointer $data = c_read($source);
my Str $value = nativecast(Str, $data);
c_free($data);
# $value is now ready to be used
I run this code through valgrind, which didn't report any attempt to reference a freed memory buffer. Still I'm curious.
The internals for Str
are completely incompatible with C strings. So they have to be decoded before they are used.
More specifically MoarVM stores grapheme clusters as [negative] synthetic codepoints if there isn't already an NFC codepoint for them. This means that even two instances of the same program may use different synthetic codepoints for the same grapheme cluster.
Even ignoring that, MoarVM stores strings as immutable data structures. Which means that it can't just use the C string, as C code may change it out from under MoarVM breaking that assumption.
I'm sure there are a bunch more reasons that it can't use C strings as-is.
Like I said, the internals of Str
are completely incompatible with C strings. So there is zero chance of it continuing to use the space allocated by the C function.
The biggest problem here would be to call nativecast
after freeing the buffer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With