1
0

feat: update cdylib cstr ffi module

This commit is contained in:
2026-05-10 16:43:25 +08:00
parent 7f36375a73
commit 1a45b309e7
3 changed files with 17 additions and 10 deletions

View File

@@ -0,0 +1,66 @@
//! 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.
//!
//! 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;
use std::ffi::{CString, CStr, c_char};
struct StringCache {
msg: CString,
}
impl StringCache {
fn new() -> Self {
Self {
msg: CString::new("").expect("empty string must be valid for CString"),
}
}
pub fn set_msg(&mut self, msg: &str) {
self.msg = CString::new(msg).expect("unexpected blank in string push into string cache");
}
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");
}
}
thread_local! {
static STRING_CACHE: RefCell<StringCache> = RefCell::new(StringCache::new());
}
/// Set thread local string exposed for C code.
pub fn set_ffi_string(msg: &str) {
STRING_CACHE.with(|e| {
e.borrow_mut().set_msg(msg);
});
}
/// Get const pointer to thread local string exposed for C code.
pub fn get_ffi_string() -> *const c_char {
STRING_CACHE.with(|e| e.borrow().get_msg())
}
/// Clear thread local string exposed for C code.
///
/// This function usually should be called at the beginning of every exposed C functions.
pub fn clear_ffi_string() {
STRING_CACHE.with(|e| {
e.borrow_mut().clear_msg();
});
}
/// Parse string given by C code into Rust string.
pub fn parse_ffi_string<'a>(ptr: *const c_char) -> &'a CStr {
unsafe { CStr::from_ptr(ptr) }
}