#c-compatible #string-literal #literals #const #cstr #zombiezen

zombiezen-const-cstr

Create static C-compatible strings from Rust string literals

1 stable release

1.0.0 May 10, 2020

#10 in #cstr

MIT/Apache

9KB
104 lines

const-cstr

Create static C-compatible strings from Rust string literals.

This is forked from abonander/const-cstr to implement an API that conforms to the Rust API Guidelines and takes advantage of const functions to hide more implementation details.

Usage

Cargo.toml:

[dependencies]
zombiezen-const-cstr = "1.0"

Example

use zombiezen_const_cstr::{const_cstr, ConstCStr};

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

/// Declare a constant:
const HELLO_CSTR: ConstCStr = const_cstr!("Hello, world!");

// 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() {
    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