How to link c++ library to Rust*

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 :frowning:

M

Look into https://rust-lang.github.io/rust-bindgen/, which will generate the FFI bindings for you.

1 Like

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

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.