Is it possible to call C or C++ functions within Rust? If so, how is this done?
相关问题
- Sorting 3 numbers without branching [closed]
- Multiple sockets for clients to connect to
- How to compile C++ code in GDB?
- Why does const allow implicit conversion of refere
- thread_local variables initialization
Rust can link to/call C functions via its FFI, but not C++ functions.
While I don't know why you can't call C++ functions, it is probably because C++ functions are complicated.
Rust doesn't support this directly, C++ function symbol mangling is implementation defined, so it will need a lot of support from Rust to handle this feature. It's not impossible but it's probably not going to happen.
However, Rust claims to support the C language. This is clearly more easy to support, as it "only" needs to support the function calls of C. This is implementation-defined behavior too, but this doesn't change a lot and people agree to work together to share the same convention so you will not have a problem to use C as intermediary on common platform.
So, to call C++ from Rust, you must pass by C.
To call C from Rust, the docs show this example:
To call C++ from C, the docs show this example:
To transmute this example to our example in Rust, that gives: