Is it possible to call C or C++ functions within Rust? If so, how is this done?
Calling C code from Rust falls under FFI (Foreign Function Interface) and is unsafe by nature, as it's crossing Rust boundary and all the checks that comes with it.
Interoperability with foreign code Rust guarantees that the layout of a struct is compatible with the platform's representation in C only if the #[repr(C)] attribute is applied to it.
Use rustc to compile your program to the RISC V target. (Use RISC V because it is so simple) Implement a RISC V instruction to C function generator. Convert the RISC V binary produced in 1) to C using the function generator created in 2)
However, Rust programs also optimize quite well, sometimes better than C. While C is good for writing minimal code on byte-by-byte pointer-by-pointer level, Rust has powerful features for efficiently combining multiple functions or even whole libraries together.
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:
extern "C" {
fn abs(input: i32) -> i32;
}
fn main() {
unsafe {
println!("Absolute value of -3 according to C: {}", abs(-3));
}
}
To call C++ from C, a C++ function must be defined like this:
// This C++ function can be called from C code
extern "C" void handler(int) {
std::cout << "Callback invoked\n"; // It can use C++
}
To transmute this example to our example in Rust, that gives:
#include <cstdlib>
#include <cinttypes>
extern "C" std::int32_t abs(std::int32_t n) {
return std::abs(static_cast<std::intmax_t>(n));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With