1
0
Files
wfassoc/wfassoc-cdylib/src/cstr_ffi.rs

101 lines
2.8 KiB
Rust
Raw Normal View History

2025-11-26 22:40:17 +08:00
//! When calling this dynamic library with outside programs,
//! outer programs may usually need to fetch string resource produced by Rust code.
//! However it is impossible pass Rust string directly to outer program.
2026-05-10 16:55:09 +08:00
//!
2025-11-26 22:40:17 +08:00
//! This module provide **thread independent** string cache for resolving this issue.
//! When we need pass string to outer programs, we push that string into this string as C-like format,
//! then return its pointer to outer program.
//! So that outside program can utilize it like calling C/C++ library.
//! The only thing that outer programs should note is that this string is volatile,
//! once they get it, they must dupliate it immediately before any futher calling to this dynamic library.
use std::cell::RefCell;
2026-05-10 16:55:09 +08:00
use std::ffi::{CStr, CString, c_char};
use thiserror::Error as TeError;
2025-11-26 22:40:17 +08:00
2026-05-10 16:55:09 +08:00
// region: Error
/// Error occurs in this crate.
#[derive(Debug, TeError)]
pub enum Error {
#[error("unexpected NUL when parsing into C/C++ string")]
UnexpectedNul(#[from] std::ffi::NulError),
#[error("given string pointer is nullptr when parsing from C/C++ string")]
NullPtr,
#[error("invalid UTF8 sequence when parsing from C/C++ string")]
InvalidEncoding(#[from] std::str::Utf8Error),
}
/// Result type used in this crate.
type Result<T> = std::result::Result<T, Error>;
// endregion
// region: FFI String
struct FfiString {
2025-11-26 22:40:17 +08:00
msg: CString,
}
2026-05-10 16:55:09 +08:00
impl FfiString {
2025-11-26 22:40:17 +08:00
fn new() -> Self {
Self {
msg: CString::new("").expect("empty string must be valid for CString"),
}
}
2026-05-10 16:55:09 +08:00
pub fn set_msg(&mut self, msg: &str) -> Result<()> {
self.msg = CString::new(msg)?;
Ok(())
2025-11-26 22:40:17 +08:00
}
pub fn get_msg(&self) -> *const c_char {
self.msg.as_ptr()
}
pub fn clear_msg(&mut self) {
self.msg = CString::new("").expect("empty string must be valid for CString");
}
}
2026-05-10 16:55:09 +08:00
// endregion
// region: Exposed Functions
2025-11-26 22:40:17 +08:00
thread_local! {
2026-05-10 16:55:09 +08:00
static STRING_CACHE: RefCell<FfiString> = RefCell::new(FfiString::new());
2025-11-26 22:40:17 +08:00
}
2026-05-10 16:43:25 +08:00
/// Set thread local string exposed for C code.
2026-05-10 16:55:09 +08:00
pub fn set_ffi_string(msg: &str) -> Result<()> {
2025-11-26 22:40:17 +08:00
STRING_CACHE.with(|e| {
2026-05-10 16:55:09 +08:00
e.borrow_mut().set_msg(msg)
})
2025-11-26 22:40:17 +08:00
}
2026-05-10 16:43:25 +08:00
/// Get const pointer to thread local string exposed for C code.
pub fn get_ffi_string() -> *const c_char {
2025-11-26 22:40:17 +08:00
STRING_CACHE.with(|e| e.borrow().get_msg())
}
2026-05-09 16:27:04 +08:00
2026-05-10 16:43:25 +08:00
/// Clear thread local string exposed for C code.
2026-05-10 16:55:09 +08:00
///
2026-05-10 16:43:25 +08:00
/// This function usually should be called at the beginning of every exposed C functions.
pub fn clear_ffi_string() {
2026-05-09 16:27:04 +08:00
STRING_CACHE.with(|e| {
e.borrow_mut().clear_msg();
});
}
2026-05-10 16:43:25 +08:00
/// Parse string given by C code into Rust string.
2026-05-10 16:55:09 +08:00
pub fn parse_ffi_string<'a>(ptr: *const c_char) -> Result<&'a str> {
if ptr.is_null() {
Err(Error::NullPtr)
} else {
let c_str = unsafe { CStr::from_ptr(ptr) };
Ok(c_str.to_str()?)
}
2026-05-10 16:43:25 +08:00
}
2026-05-10 16:55:09 +08:00
// endregion