How to Use CString and CStr for FFI in Rust

Use CString to send Rust strings to C and CStr to read C strings back into Rust safely.

Use CString::new to convert a Rust string into a null-terminated C string for FFI, and use CStr::from_ptr to convert a C string pointer back into a Rust &CStr.

use std::ffi::{CStr, CString};
use std::os::raw::c_char;

// Rust -> C: Create a CString from a &str
let rust_str = "Hello";
let c_str = CString::new(rust_str).unwrap();

// C -> Rust: Create a &CStr from a *const c_char
let c_ptr: *const c_char = c_str.as_ptr();
let rust_cstr = unsafe { CStr::from_ptr(c_ptr) };
let rust_string = rust_cstr.to_string_lossy();