FFI Structs
Foreign Function Interface types
CString
Section titled “CString”use std::ffi::CString;
fn main() { // CString - owned C string (null-terminated) let c_string = CString::new("Hello, C!").expect("CString::new failed");
println!("=== CString ==="); println!("as_ptr(): {:?}", c_string.as_ptr()); println!("as_bytes(): {:?}", c_string.as_bytes()); println!("as_bytes_with_nul(): {:?}", c_string.as_bytes_with_nul());
// To/from Rust string let rust_str = c_string.to_str().expect("Invalid UTF-8"); println!("to_str(): {}", rust_str);
// Into raw pointer (for passing to C) let ptr = c_string.into_raw(); println!("\ninto_raw(): {:?}", ptr);
// Reclaim ownership let c_string = unsafe { CString::from_raw(ptr) }; println!("Reclaimed: {:?}", c_string.to_str());
// Error case: interior null let result = CString::new("Hello\0World"); println!("\n=== Interior Null ==="); println!("CString::new with \\0: {:?}", result);
// Vec to CString let bytes = vec![72, 101, 108, 108, 111]; // "Hello" let c_string = CString::new(bytes).unwrap(); println!("\nFrom Vec: {:?}", c_string.to_str());}เข้าสู่ระบบเพื่อดูเนื้อหาเต็ม
ยืนยันตัวตนด้วยบัญชี Google เพื่อปลดล็อกบทความทั้งหมด
Login with Google