#string-literal #literals #c-compatible

const-cstr

Create static C-compatible strings from Rust string literals

4 releases (2 breaking)

Uses old Rust 2015

0.3.0 Feb 10, 2018
0.2.1 Jul 30, 2016
0.2.0 Jul 30, 2016
0.1.0 Sep 28, 2015

#6 in #c-compatible

Download history 13189/week @ 2023-11-21 15929/week @ 2023-11-28 12518/week @ 2023-12-05 15160/week @ 2023-12-12 10999/week @ 2023-12-19 7087/week @ 2023-12-26 14752/week @ 2024-01-02 13782/week @ 2024-01-09 15442/week @ 2024-01-16 15089/week @ 2024-01-23 13621/week @ 2024-01-30 13911/week @ 2024-02-06 16218/week @ 2024-02-13 16168/week @ 2024-02-20 16152/week @ 2024-02-27 13900/week @ 2024-03-05

64,362 downloads per month
Used in 89 crates (46 directly)

MIT/Apache

9KB
65 lines

const-cstr

Create static C-compatible strings from Rust string literals.

Usage

Cargo.toml:

[dependencies]
const-cstr = "0.1"

Crate root:

#[macro_use] extern crate const_cstr;

Example

 #[macro_use] extern crate const_cstr;

 use std::os::raw::c_char;
 use std::ffi::CStr;

 const_cstr! {
     HELLO_CSTR = "Hello, world!";

     // Multiple declarations can be made with one invocation.
     // GOODNIGHT_CSTR = "Goodnight, sun!";

     // But only with the same visibility:
     // pub GOODNIGHT_CSTR = "Goodnight, sun!";
     // ^~~ Error: expected identifier, found `pub` 
 }

 // Imagine this is an `extern "C"` function linked from some other lib.
 unsafe fn print_c_string(cstr: *const c_char) {
     println!("{}", CStr::from_ptr(cstr).to_str().unwrap());
 }

 fn main() {
     // When just passed a literal, returns an rvalue instead.
     let goodnight_cstr = const_cstr!("Goodnight, sun!");

     unsafe {
         print_c_string(HELLO_CSTR.as_ptr());
         print_c_string(goodnight_cstr.as_ptr());
     }
 }

Prints:

Hello, world!
Goodnight, sun!

License

Licensed under either of

Contribution

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you shall be dual licensed as above, without any additional terms or conditions.

No runtime deps