The returned pointer will be valid for as long as self is and points
to a contiguous region of memory terminated with a 0 byte to represent
the end of the string.
Dereferencing it or passing it to a foreign function requires unsafe.
Still, CString::as_ptr() leads to common use after free errors in Rust.
It is a recurring gotcha, and we can't ignore this just because it requires an unsafe { } block to produce.
Interop with FFI in general seems to be an increasingly common stumbling block. There’s little out there about how to, for example, return a generated C string or deal with arrays.
I’m trying to whip an FFI binding generator into shape so we can just tell people “run this on your crate and it will generate the correct .h/.py/.rb binding for you”, though that doesn’t help with the above.
Maybe we also need a standard (or at least, blessed) FFI module/crate that has helpers for the less trivial but very common use cases, and have the book and docs point to that. At least then we’ll have something to point people to on SO other than saying “uh… you’re kinda on your own, good luck.”
I can see two reasonable models. One is to call CString::into_ptr, then call CString::from_ptr to free the string. The other is to encourage people to write bindings like extern { pub fn strlen(s: &CStr) -> libc::size_t; } instead of using raw pointers.
&CStr doesn’t actually work correctly at the moment, but it should be easy to fix. Some sort of CSlice would probably be a good companion to CStr.
I think the "construct a CString, then call as_ptr()" pattern is floating around simply because there isn’t a better alternative at the moment; neither of the above models is usable with stable Rust. If you’re familiar with C++, it isn’t such a big deal: std::string has a data() method which gets used all the time. That said, only a C++ programmer would consider this pattern a good idea.
So actually, it turns out fixing CStr is harder than I thought… but if anyone wants to experiment, it’s possible to approximate a fixed &CStr with something like the following:
Unlike the current DST CStr, with an unsized type, &CStr would be a thin pointer that can be used for FFI.
However, Rust currently doesn’t support unsized types – it only has statically sized types (Sized) and dynamically sized types (DST). Since removing Sized from a type is a breaking change, CStr was made dynamically sized so that it can be turned unsized in the future.
Using a ...Ref<'a> instead of a real reference avoids the need for unsized types in the language, but it shouldn’t be added to the standard library as long as there’s a chance we’ll get real unsized types.