Hacker News new | ask | show | jobs
by jihiggins 646 days ago
For going from C to Rust, I think you'd just use CString::to_str instead of CString::to_string. I'm pretty sure this just calls std::transmute behind the scenes and doesn't cause an allocation. (In the same way that you generally don't clone vanilla strings and instead pass references around.) iirc, it's still tricky to go the other way. I think if I was working with super C-FFI heavy code, I'd just end up using CString as my default for that code. Custom allocators would also help there, since you could just create the strings on the stack or whatever, but I don't remember if the string version of those is even finished in nightly yet.
2 comments

You'd use CStr::from_ptr if you've received a C string (which does not allocate, that's correct, though not via transmute, just a cast), but since Rust strings aren't null terminated, you'll need to allocate some memory to add the null byte on the end. Which yeah, then I'd want to try to use CString as much as possible, in that case.

(If you wrote to an array on the stack, you could turn it into a Cstr too, instead of heap allocating, but then you'd have a max string size, which may or may not be something you'd want.)

alloc::string::String (a.k.a. std::string::String) doesn't support custom allocators yet, even on nightly, but that doesn't mean you can't use them; it just means you have to use a third-party crate, like https://docs.rs/string or https://docs.rs/smol_str.