In the first step you should choose "main" crate that would be the bridge between Rust and other language.
It should have crate-type
cdylib
or staticlib
, see suitable Rust book's section for a detailed description.
For example:
[lib]
name = "cpp_example_rust_part"
crate-type = ["cdylib"]
Then you should create build.rs
inside this crate.
For example:
//build.rs
use flapigen::{CppConfig, CppOptional, CppStrView, CppVariant, LanguageConfig};
use std::{env, path::Path};
fn main() {
let out_dir = env::var("OUT_DIR").expect("no OUT_DIR, but cargo should provide it");
//ANCHOR: cpp_config
let cpp_cfg = CppConfig::new(
// ANCHOR: cpp_output
Path::new("..").join("cpp-part").join("rust-api"),
// ANCHOR_END: cpp_output
"rust".into(),
)
.cpp_optional(CppOptional::Boost)
.cpp_variant(CppVariant::Boost)
.cpp_str_view(CppStrView::Boost);
//ANCHOR_END: cpp_config
let swig_gen = flapigen::Generator::new(LanguageConfig::CppConfig(cpp_cfg));
swig_gen.expand(
"c++-api-for-rust",
// ANCHOR: rust_input
Path::new("src/cpp_glue.rs.in"),
// ANCHOR_END: rust_input
// ANCHOR: rust_output
&Path::new(&out_dir).join("cpp_glue.rs"),
// ANCHOR_END: rust_output
);
println!(
"cargo:rerun-if-changed={}",
Path::new("src").join("cpp_glue.rs.in").display()
);
}
Here you instruct flapigen
to generate C++/Rust code from "src/cpp_glue.rs.in" as input:
Path::new("src/cpp_glue.rs.in"),
and we specify our output, Rust file:
&Path::new(&out_dir).join("cpp_glue.rs"),
directory for C++ files:
Path::new("..").join("cpp-part").join("rust-api"),
You can find a detailed description of code generation in the suitable Cargo book section.
Then you should create a file for the "foreign" language API description. For example:
use super::{f2, Foo};
foreign_class!(class Foo {
self_type Foo;
constructor Foo::new(_: i32) -> Foo;
fn Foo::set_field(&mut self, _: i32);
fn Foo::f(&self, _: i32, _: i32) -> i32;
fn f2(_: i32) -> i32;
});
And connect the generated code with your crate exactly how as in the Cargo book :
// src/lib.rs
mod cpp_glue;
pub use crate::cpp_glue::*;
// src/cpp_glue.rs
include!(concat!(env!("OUT_DIR"), "/cpp_glue.rs"));
Do not forget to add flapigen
as a dependency into [build-dependencies]
section of your crate's Cargo.toml
file and you are ready to go.