rustffi

Is there any way to create a const &'static CStr?


I haven't found anything in the standard library about how to make a const &'static CStr. I've tried to make my own macro to convert a &'static str literal to a &'static CStr:

macro_rules! cstr {
    ($e: expr) => {{
        const buffer: &str = concat!($e, "\0");
        unsafe {std::ffi::CStr::from_bytes_with_nul_unchecked(buffer.as_bytes())}
    }}                                                                           
}     

It has a couple problems:

  1. If expr contains a null byte, it invokes undefined behavior
  2. str::as_bytes is not const, so the &CStr is not const

Solution

  • Since Rust 1.77.0, on edition 2021 and forwards, you can create &CStr literals with the c prefix:

    const FOO: &core::ffi::CStr = c"Hello, world!";
    

    This allows using escapes (even non-UTF-8), checks for interior NUL bytes (and rejects them), and properly adds a trailing NUL.

    On older versions, you can use the cstr crate:

    const FOO: &core::ffi::CStr = cstr::cstr!(b"Hello, world!");