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

2019-04-08 19:07发布

问题:

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

回答1:

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.



回答2:

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, the docs show this example:

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


标签: c++ c rust