Rust and C++ FFI integration

#1

Are the following statements an accurate representation of Rust/C++ FFI integration?

  1. If you use bindgen, expect to blacklistwhitelist lots of std::*

  2. If you want to call a templated C!+ function, you need to instantiate the template with the various arg combinitions you intend to use and have different externed names for each of them.

Thanks!

#2

My $.02 is if you want to (relatively painlessly) use C++ code from Rust, expose a C API (and ABI) from the C++ code, and use that for interop. Essentially, the same thing you’d do to expose Rust code via FFI.

Sometimes you don’t have this choice, but if presented with it, I feel that’s the path with less headache along the way.

3 Likes
#3

How do you deal with C++ structs/class that takes template arguments? Do you instantiate every combo you might use?

#4

Yes, there’s no way (in any language) of avoiding that (at least without the capability to somehow invoke a real C++ compiler, or emulate most or all of one).

2 Likes
#5

Instantiating everything you want to expose with a C api is probably the best idea. It’s relatively straightforward and doesn’t have surprising failure modes.

Unless you are a C++ compiler, generating proper C++ bindings is extraordinarily difficult, and personally I wouldn’t deploy automatically generated c++ bindings to production (bindgen has problems with some complex-but-common template features and inheritance, for example). It seems like there’a lot of pain using these bindings as well.

I think Rust => C++ is much easier, and while I don’t know your use case that might be an approach worth considering.

2 Likes