Rust C++ FFI suggestions

⚓ Rust    📅 2025-12-05    👤 surdeus    👁️ 1      

surdeus

Info

This post is auto-generated from RSS feed The Rust Programming Language Forum - Latest topics. Source: Rust C++ FFI suggestions

Hi 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_view and variant. This seems to be a daunting task given the structure of cxx and the opinionated nature of this lib. In addition, for something like string_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 for variant. 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

Read full topic

🏷️ Rust_feed