rust-cpp
rust-cpp is a build tool & macro which enables you to write C++ code inline in your rust code.
NOTE: This crate works on stable rust, but it is not stable itself. You can use this version all you want, but don't be surprised when a 0.2 release is made which completely breaks backwords compatibility. I view this crate as more of an experiment than a product.
As the tools come into stable rust to make this more practical to use, I expect that it will stabilize. Namely, I do not expect that this module will have a stable-ish interface until we get a stable procedural macro system.
Setup
Add cpp
as a dependency to your project. It will need to be added both as a
build dependency, and as a normal dependency, with different flags. You'll also
need a build.rs
set up for your project.
[]
# ...
= "build.rs"
[]
# ...
= { = "0.1.0", = ["build"] }
[]
# ...
= { = "0.1.0", = ["macro"] }
You'll also then need to call the cpp
build plugin from your build.rs
. It
should look something like this:
extern crate cpp;
Usage
In your crate, include the cpp crate macros:
extern crate cpp;
Then, use the cpp!
macro to define code and other logic which you want shared
between rust and C++. The cpp!
macro supports the following forms:
cpp!
cpp
also provides a header which may be useful for interop code. This header
includes <cstdint>
, which means that a sufficiently modern C++ compiler may be
required to use it. This header, rust_types.h
, can be included with:
cpp!
It provides the rs
namespace, which contains various type definitions for rust
types, such as the numeric types (rs::i8
, rs::u64
, rs::f32
, rs::usize
,
etc.), the rust slice type (&[u8] => rs::Slice<rs::u8>
), and the rust trait
object fat pointer type. There are also definitions for rs::bool_
, which is
guaranteed to be 1 byte wide, the size of a rust bool
, and rs::char_
which
is the size of a rust char
. The full body of rust_types.h
is included below.
Warning about Macros
rust-cpp cannot identify and parse the information found in cpp! blocks which
are generated with macros. These blocks will correctly generate rust code, but
will not generate the corresponding C++ code, most likely causing your build to
fail with a linker error. Do not create cpp! {}
blocks with macros to avoid
this.