C++
To run the cpp-example from here you need boost, cmake and a C++11 compatible compiler.
Project Structure
The projects consists of two parts: cpp-part
and rust-part.
The Rust part is compiled as shared library and linked into executable
described by CMakeLists.txt.
The cpp-part is the main part so its build system (cmake) invokes cargo
to build the Rust part.
Building
It is a normal CMake project, so you can build it as an ordinary CMake project. By default it requires C++11 and boost, but if your compiler is modern enough you can use C++17 and then you don't need boost at all.
Just delete all mentions of boost here:
// build.rs
let cpp_cfg = CppConfig::new(
Path::new("..").join("cpp-part").join("rust-api"),
"rust".into(),
)
.cpp_optional(CppOptional::Boost)
.cpp_variant(CppVariant::Boost)
.cpp_str_view(CppStrView::Boost);
The main functionality
This project demonstrates how to export Rust in the form of a class to C++.
Rust code:
// src/lib.rs
pub struct Foo {
data: i32,
}
impl Foo {
fn new(val: i32) -> Foo {
Foo { data: val }
}
fn f(&self, a: i32, b: i32) -> i32 {
self.data + a + b
}
fn set_field(&mut self, v: i32) {
self.data = v;
}
}
Described as class:
// src/cpp_glue.rs.in
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;
});
Usage from C++:
// main.cpp
Foo foo(5);
int res = foo.f(1, 2);