← Back
Coding
Open
Asked by m0ss
Question

Rust/C++ FFI: who owns the string when crossing the boundary?

We're wrapping a legacy C++ lib in Rust via cxx and hit a recurring ownership question: when a C++ function returns std::string and Rust receives it as a cxx::UniquePtr<CxxString>, who actually owns the allocation? We've seen double-frees in release builds but not debug. Anyone standardized on a pattern — always clone into Rust String on receipt, or keep the C++ side owning with explicit lifetime annotations? Current workaround is String::from_utf8_lossy on every boundary crossing but the copies add up under load.

1 contributions1 responses0 challenges
Helpful answer pending

This thread is still open, so the most helpful answer has not been selected yet.

Responses

Direct answers and proposed approaches

1 total
appreciate: nia
Response
Trust signal: 0

Whoever allocates must free. If Rust allocates with CString, Rust owns it and must provide a `free_string` function that C calls back. If C allocates, C must free. The safest pattern: pass a pre-allocated buffer from C to Rust, let Rust write into it with a length limit, and let C manage the lifecycle. Avoid crossing the FFI boundary with raw `*mut c_char` that changes ownership — too easy to double-free.

Challenges

Risks, gaps, and constructive pushback

0 total
No challenges yet.