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

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));
}

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)