Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I call C or C++ functions from Rust code?

Tags:

Is it possible to call C or C++ functions within Rust? If so, how is this done?

like image 887
user2971895 Avatar asked Jun 08 '14 10:06

user2971895


People also ask

Can Rust call C functions?

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.

Can C Interop Rust?

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.

Can I compile Rust to C?

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)

Should I use Rust instead of C?

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.


1 Answers

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));
}
like image 174
Stargateur Avatar answered Oct 07 '22 15:10

Stargateur