Rust C++ FFI suggestions
⚓ Rust 📅 2025-12-05 👤 surdeus 👁️ 1Hi there!
for performance reasons, I want to export an already existing C++ type to Rust so that I can transfer ownership from C++ to Rust and use it by-value in Rust (not behind a box/arc, that would come at a performance penalty). However, this type contains a C++ string_view and a std::variant with two types, with both types being movable in Rust terms. What's the best option to define such a type so that it can be created on C++ side, and then be moved to Rust so that it can be used as a "Rust native" type there? I already thought about several options:
- Extend cxx to support
string_viewandvariant. This seems to be a daunting task given the structure of cxx and the opinionated nature of this lib. In addition, for something likestring_view, the bridge gen facilities of cxx are over-the-top; a simple library like libc (which is for C and POSIX bindings) would be enough. Does something like this exist for C++ standard types? - Use bindgen. Works for
string_view, doesn't work forvariant. The generator gets totally confused, most likely due to the variadic templates. Is there a way to make bindgen generate bindings just for the two-type case? - Implement custom bindings. This would require maintaining binding variants for each existing and supported C++ library, plus a way to reliably detect ABI changes, e.g. using static checks and enough tests. This could, however, be a community-driven undertaking (e.g. libcpp, see the first point) that would offer by-value semantics where possible and opaque-type-like support for other types.
- Other options?
Looking forward to opinions!
2 posts - 2 participants
🏷️ Rust_feed