//! ch10 · Rust 侧:`extern "C"` + `#[no_mangle]` 导出 C ABI。 //! //! Rust 的默认 ABI 是不稳定的 Rust ABI,Dart 无法调用; //! 必须显式声明 `extern "C"` 并禁止名字修饰(`#[no_mangle]`)。 use std::ffi::{CStr, CString}; use std::os::raw::c_char; /// 数值:基本传参与返回值。 #[no_mangle] pub extern "C" fn add_i32(a: i32, b: i32) -> i32 { a.wrapping_add(b) } #[no_mangle] pub extern "C" fn mul_f64(a: f64, b: f64) -> f64 { a * b } /// 字符串:入参是 `*const c_char`(Dart 侧 toNativeUtf8 分配), /// 返回值由 `CString::into_raw` 交给调用方,必须用 `free_string` 归还。 #[no_mangle] pub extern "C" fn concat_strings(a: *const c_char, b: *const c_char) -> *mut c_char { if a.is_null() || b.is_null() { return std::ptr::null_mut(); } // SAFETY: 调用方保证指针指向合法的 NUL 结尾字符串。 let left = unsafe { CStr::from_ptr(a) }.to_string_lossy(); let right = unsafe { CStr::from_ptr(b) }.to_string_lossy(); match CString::new(format!("{left}{right}")) { Ok(s) => s.into_raw(), Err(_) => std::ptr::null_mut(), } } /// SAFETY: `s` 必须来自 `concat_strings`(即 `CString::into_raw` 的产物),且只能释放一次。 #[no_mangle] pub unsafe extern "C" fn free_string(s: *mut c_char) { if !s.is_null() { drop(CString::from_raw(s)); } } /// 回调:直接接收 C 函数指针并调用。 #[no_mangle] pub extern "C" fn apply_cb(cb: extern "C" fn(i32) -> i32, x: i32) -> i32 { cb(x) }