While Rust's native strings are better in general, there's a lot of existing C APIs that need null-terminated strings.
It's good that CStr
exists and it's what I'd turn to for dynamic strings. But it's pretty inconvenient if I need a static string literal, a case which was pretty common for my application (OpenGL) and I can see being useful for many C APIs.
I ended up writing a macro like this:
macro_rules! cstr {
($str:expr) => (CStr::from_bytes_with_nul_unchecked(concat!($str, "\0").as_bytes()))
}
I could then use it like this:
let pos_attrib = gl::GetAttribLocation(program, cstr!("position").as_ptr());
Does anyone have any thoughts about whether this could be in the standard library, or why it isn't already? Also, if there's already a better way of doing this, I'd love to know. I know I could write "foo\0"
manually but it feels unclean.