from-scratch/lang/tests/int_to_str.rs
2025-10-28 21:05:16 +01:00

35 lines
813 B
Rust

#[unsafe(no_mangle)]
extern "C" fn panic() -> ! {
panic!("Called panic from external code.");
}
#[repr(C)]
struct FFISlice {
ptr: *const u8,
len: usize,
}
impl FFISlice {
fn as_slice(&self) -> &[u8] {
unsafe { core::slice::from_raw_parts(self.ptr, self.len) }
}
fn as_str(&self) -> &str {
unsafe { core::str::from_utf8_unchecked(self.as_slice()) }
}
}
unsafe extern "C" {
unsafe fn int_to_str2(value: usize, buffer: *mut u8, buffer_len: usize) -> FFISlice;
}
fn main() {
let value = 1234567890usize;
let mut buffer = [0u8; 32];
unsafe {
let slice = int_to_str2(value, buffer.as_mut_ptr(), buffer.len());
let s = slice.as_str();
println!("Integer: {}, String: {}", value, s);
assert_eq!(s, value.to_string());
}
}