Can I interface with C++ through a C interface?


So, I’m wondering if it’s possible to write some C code that makes calls to C++ code as a way to get around Rust not supporting calls directly into C++.

Seems like yes:

If so, maybe that should be added to the FFI piece of the tutorial?

Thank you!


You actually shouldn’t need a C shim. If the C++ code exports an interface callable by C, then it should be callable by Rust as well. Granted, I’ve written a lot more Rust than C or C++ so I may not entirely know what I’m talking about.

In fact, a convenient example of Rust calling into C++ would be the LLVM wrapper for the Rust compiler itself and the bindings to it in Rust.

So you just declare bare extern "C" functions in your C++ code and declare them in an extern block in your Rust code. You can pass C++ pointers to Rust as long as the Rust code doesn’t try to dereference them or free them. If that’s what you meant, I must have misread. TL;DR: yes.