[][src]Macro autocxx::include_cxx

include_cxx!() { /* proc-macro */ }

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_cxx!(
    Header("input.h"),
    Allow("do_math"),
);

ffi::cxxbridge::do_math(3);

Configuring the build

To build this, you'll need to:

  • Educate the procedural macro about where to find the C++ headers. Set the AUTOCXX_INC environment variable to a list of directories to search.
  • Build the C++ side of the bindings. You'll need to use the autocxx-gen crate (or similar) to process the same .rs code into C++ header and implementation files.

Syntax

Within the brackets of the include_cpp!(...) macro, you should provide a list of the following:

  • Header(filename): a header filename to parse and include
  • Allow(type or function name): a type or function name whose declaration should be made available to C++.
  • AllowPOD(type name): a struct name whose declaration should be made available to C++, and whose fields are sufficient simple that they can allow being passed back and forth by value (POD = 'plain old data').

How to allow structs

A C++ struct can be listed under 'Allow' or 'AllowPOD' (or may be implicitly 'Allowed' because it's a type referenced by something else you've allowed.)

The current plan is to use 'Allow' under normal circumstances, but 'AllowPOD' only for structs where you absolutely do need to pass them truly by value and have direct field access. Some structs can't be represented as POD, e.g. those containing std::string due to self-referential pointers. We will always handle such things using UniquePtr to an opaque type in Rust, but still allow calling existing C++ APIs which take such things by value - we'll aim to generate automatic unwrappers. This won't work in all cases. The majority of this paragraph doesn't work at all yet, and it will never work for some cases. It remains to be seen whether this is good enough in practice.

Generated code

You will find that this macro expands to the equivalent of:

mod ffi {
    pub mod cxxbridge {
        pub fn do_math(a: u32) -> u32
    }

     pub const kMyCxxConst: i32 = 3;

     pub mod defs {
         pub const MY_PREPROCESSOR_DEFINITION: i64 = 3i64;
     }
}