4 ms·
You can call into Rust directly from C++ (with a header file). But yeah, the reverse requires a C layer. rust-bindgen has experimental C++ support which we use
by Manishearth 11y ago
You can call into Rust directly from C++ (with a header file).
But yeah, the reverse requires a C layer. rust-bindgen has experimental C++ support which we use for spidermonkey but it isn't perfect.
- sitkack 11y ago> You can call into Rust directly from C++ (with a header file). Can you tell me more about this?
- steveklabnik 11y agoThis is C and I tossed it together VERY quickly but $ cat hello.rs #[no_mangle] pub extern fn plus_one(x: isize) -> isize { x + 1 } $ cat hello.c #include<stdio.h> extern int plus_one(int); int main() { int result = plus_one(5); printf("result is %d\n", result); return 0; } $ rustc hello.rs --crate-type=dylib $ gcc hello.c -lhello -L . $ LD_LIBRARY_PATH=. ./a.out result is 6
- sitkack 11y agoI get the calling into Rust from C via no_mangle + extern. I was looking for the header only C++ to Rust path.
- steveklabnik 11y agoHm, I might have misunderstood either you or the OP, then. A C++ header would include the same extern declaration, though it would mark it with the C ABI as well.
- Manishearth 11y agoIt's the same way you call into C from C++. When Rust has a no_mangle extern C function to the universe it's just a C function. Your C++ header just needs to mark the fn as extern C and you're done, you can call it as you would call any other C/++ function.
- sitkack 11y agoOh, I thought there was a magical way to call from C++ into Rust using only a C++ header w/o no_mangle/extern.