mrmxs
December 20, 2019, 12:40pm
1
How to link c++ library to Rust? Let say I have written a c++ lib compiled it into libmylib.o using a make file and now I want to call its functions from my rust src?
Please help, I lost so much time in exploring various options but failing so many ways..
even if someone could show me how to start on a simple project structure below, I would be so much grateful:
my c/cpp code
#include <stdint.h>
#ifdef FOO
#if BAR == 1
int32_t foo() {
return 4;
}
#endif
#endif
my Project structure:
src -+ lib.rs
+ foo.c
Cargo.toml
build.rs
I am not purposely putting structures I tried because apparently everything I tried does not work.. Please help
M
jyn514
December 20, 2019, 12:52pm
2
Look into Introduction - The `bindgen` User Guide , which will generate the FFI bindings for you.
1 Like
Yandros
December 20, 2019, 7:14pm
3
In Rust you cannot #include "c_declarations.h"
, instead you need to explicitely have somewhere in the code such declarations written in Rust:
Taking your
extern "C" { // if C++, if just C no need for extern "C"
int32_t foo() {
return 4;
}
}
its declaration / signature is:
extern "C" {
int32_t foo();
}
which in Rust gives:
extern "C" {
fn foo () -> i32;
}
As @jyn514 suggested, bindgen
is a great tool to automate this task, which is not only tedious but easy to mess up.
For more information about this: look use the FFI "keyword" in your searches, you should find quite a bit of info around. For instance:
2 Likes
system
Closed
March 19, 2020, 7:14pm
4
This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.