Macro autocxx::include_cpp

source ·
macro_rules! include_cpp {
    (
        $(#$include:ident $lit:literal)*
        $($mac:ident!($($arg:tt)*))*
    ) => { ... };
}
Expand description

Include some C++ headers in your Rust project.

This macro allows you to include one or more C++ headers within your Rust code, and call their functions fairly naturally.

Examples

C++ header (input.h):

#include <cstdint>

uint32_t do_math(uint32_t a);

Rust code:

include_cpp!(
   #include "input.h"
   generate!("do_math")
   safety!(unsafe)
);

ffi::do_math(3);

The resulting bindings will use idiomatic Rust wrappers for types from the cxx crate, for example cxx::UniquePtr or cxx::CxxString. Due to the care and thought that’s gone into the cxx crate, such bindings are pleasant and idiomatic to use from Rust, and usually don’t require the unsafe keyword.

For full documentation, see the manual.

The include_cpp macro

Within the braces of the include_cpp!{...} macro, you should provide a list of at least the following:

  • #include "cpp_header.h": a header filename to parse and include
  • generate!("type_or_function_name"): a type or function name whose declaration should be made available to C++. (See the section on Allowlisting, below).
  • Optionally, safety!(unsafe) - see discussion of safety.

Other directives are possible as documented in this crate.

Now, try to build your Rust project. autocxx may fail to generate bindings for some of the items you specified with generate directives: remove those directives for now, then see the next section for advice.

Allowlisting

How do you inform autocxx which bindings to generate? There are three strategies:

  • Recommended: provide various generate directives in the include_cpp macro. This can specify functions or types.
  • Not recommended: in your build.rs, call Builder::auto_allowlist. This will attempt to spot uses of FFI bindings anywhere in your Rust code and build the allowlist that way. This is experimental and has known limitations.
  • Strongly not recommended: use generate_all. This will attempt to generate Rust bindings for any C++ type or function discovered in the header files. This is generally a disaster if you’re including any remotely complex header file: we’ll try to generate bindings for all sorts of STL types. This will be slow, and some may well cause problems. Effectively this is just a debug option to discover such problems. Don’t use it!

Internals

For documentation on how this all actually works, see IncludeCppEngine within the autocxx_engine crate.