How to Manage Memory Across FFI Boundaries

Use Box and raw pointers to explicitly transfer memory ownership between Rust and foreign languages.

Manage memory across FFI boundaries by explicitly transferring ownership using Box<T> to allocate on the heap and std::ptr to pass raw pointers, ensuring the receiving side knows who is responsible for freeing the memory.

use std::ptr;

// Rust side: Allocate on heap and leak to C (or pass ownership)
fn create_string() -> *mut i8 {
    let s = String::from("hello");
    let ptr = s.into_bytes().as_ptr() as *mut i8;
    // Leak the String to prevent Rust from freeing it immediately
    std::mem::forget(s);
    ptr
}

// C side (conceptual): Free the memory
// void free_string(i8* ptr) { /* free(ptr) */ }

For safe ownership transfer, define a C function to free the memory and call it from Rust using unsafe blocks when the pointer is no longer needed.