How to convert C++ Optional class to Rust Option in FFI?

Hello everybody,

I want to create Rust bindings for a C++ API that includes an Optional class, see the class here.

My question is simple: How can I convert this to a Rust-like Option in the FFI? I would really appreciate any help!

I don't think you can, at least not directly. What I mean by that is: I don't believe there is any incantation you can use (either on the C++ side, the Rust side, or even both) that can cause a C++-style optional<T> to be interpreted as a Rust-style Option<T>.

What you would need to do is convert the optional<T> into a plain C struct with a known layout using C++ code. You then pass that to Rust, which needs to have the same struct definition (marked as #[repr(C)]). Rust code can then turn that struct value into an Option<T>.

In general, Rust does not "speak" C++, and C++ does not "speak" Rust, but they both "speak" C, so that's how they need to communicate. That said, there are crates like cpp and cxx that could likely help with this.

3 Likes

Ok, that makes sense. I think I have a solution by digging through the optional<T> code. However, I will definitely take a look at the cpp/cxx crates for future work! I don't think I can use them now, because the code I want to link with uses a non-standard "optional" implementation.

Thanks for the links!

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.