Builtin macro for simple construction of `&'static CStr`

Are there any thoughts on adding the ability to construct static CStrs?

This would be helpful to smooth sending constant strings to a C API. Currently the only ways to do this are:

  • Allocate with CString::new("some string").unwrap().as_c_str(). This is not possible in const contexts or no_std.
  • Use byte strings and add the \0, communicate with API using .as_ptr() where needed (sidesteps CStr entirely)
  • Use byte strings and add the \0, then transmute to CStr (risky, especially with this discussion)
  • Use the crate cstr, which wraps the first option

It seems like there is opportunity for a builtin macro that mirrors the cstr crate, but uses a transmute option as needed to work in const contexts.

use std::ffi::cstr;

cstr!("I'm a c string")

I know that some syntax like c"This is a CStr" has been proposed before, but this is understandably controversial.

1 Like

Given the crate docs says it can be used in constants, I doubt it's wrapping the first option (allocating a CString).

1 Like

No transmute is needed, CStr::from_bytes_with_nul_unchecked is a const fn on stable: CStr in core::ffi - Rust

It's still unsafe, but calling it doesn't require relying on layout details of the &CStr reference itself.

1 Like

Awesome! I don't know how I missed that, but that resolves this

Good call - I got thrown off by the call to CString but I realize that's just inside the macro

Thank you for pointing this out! I guess this is what the cstr! crate currently does

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.