macro_rules! with_c_str {
($ptr:ident) => { ... };
}Expand description
Read a nullable C string argument as &str, classifying both ways it can fail.
Expands to a Result, so the usual form is with_c_str!(path)? inside a
catch closure. The null message is built from the argument’s own
name — with_c_str!(resource_id) reports "resource_id is null", which is the wording
the family already uses.
Use this where the entry point has no out-parameter, so that classifying a null
argument inside the closure is indistinguishable from classifying it before. Where
there is an out-parameter, check for null first and use
ffi::c_str_utf8 here instead — see
export_bytes_getter!.
§Safety
$ptr must be null or point to a NUL-terminated string. This expands to an unsafe
read, so it has to appear in an unsafe context.
unsafe fn name_length(path: *const c_char) -> Result<usize, FfiError> {
let path = unsafe { unparser_shared::with_c_str!(path) }?;
Ok(path.len())
}
let path = CString::new("a.txt").unwrap();
assert_eq!(unsafe { name_length(path.as_ptr()) }.unwrap(), 5);
assert_eq!(
unsafe { name_length(std::ptr::null()) }.unwrap_err().1,
"path is null"
);