Safely interacting with unsafe code is challenging. The C++ interoperability layer has limited safeguards in place to mitigate some sources of unsafet

Safe and efficient C++ interoperability via non-escapable types and lifetimes

submited by
Style Pass
2024-11-08 01:00:07

Safely interacting with unsafe code is challenging. The C++ interoperability layer has limited safeguards in place to mitigate some sources of unsafety including hiding some APIs (like methods returning iterators) and exposing them with an “Unsafe” suffix. Unfortunately, these are based on simple syntactic heuristics that are incomplete (like identifying methods that return pointer like objects) and therefore do not provide sufficient safety guarantees and do not provide a way to safely access those APIs.

Building on the ongoing work to express lifetimes in Swift, we propose using annotations to express lifetime information for C++ APIs. Then, the compiler can know that begin depends on vec and it should not be cleaned up before begin ‘s last use.

Moreover, the interoperability layer introduces defensive copies to extend the lifetime of collections while they are being iterated on. This has a performance cost and can result in a less ergonomic experience interacting with C++ code.

Leave a Comment