Built-in types
autocxx relies primarily on the standard cxx types.
In particular you should become familiar with cxx::UniquePtr and cxx::CxxString.
There are a few additional integer types, such as c_int,
which are not yet upstreamed to cxx. These are to support those pesky C/C++ integer types
which do not have a predictable number of bits on different machines.
C++ header:
inline int do_math(int a, int b) { return a+b; }
Rust:
use autocxx::prelude::*;
include_cpp! {
#include "input.h"
safety!(unsafe_ffi)
generate!("do_math")
}
fn main() {
assert_eq!(ffi::do_math(c_int(12), c_int(13)), c_int(25));
}
Strings
autocxx uses cxx::CxxString. However, as noted above, we can't
just pass a C++ string by value, so we'll box and unbox it automatically
such that you're really dealing with UniquePtr<CxxString> on the Rust
side, even if the API just took or returned a plain old std::string.
However, to ease ergonomics, functions that accept a std::string will
actually accept anything that
implements a trait called ffi::ToCppString. That may either be a
UniquePtr<CxxString> or just a plain old Rust string - which will be
converted transparently to a C++ string.
This trait, and its implementations, are not present in the autocxx
documentation because they're dynamically generated in your code
so that they can call through to a make_string implementation in
the C++ that we're injecting into your C++ build system.
(None of that happens if you use exclude_utilities, so don't do that.)
C++ header:
#include <string>
#include <cstdint>
inline uint32_t take_string(std::string a) { return a.size(); }
Rust:
use autocxx::prelude::*;
include_cpp! {
#include "input.h"
safety!(unsafe_ffi)
generate!("take_string")
}
fn main() {
assert_eq!(ffi::take_string("hello"), 5)
}
If you need to create a blank UniquePtr<CxxString> in Rust, such that
(for example) you can pass its mutable reference or pointer into some
pre-existing C++ API, call ffi::make_string("") which will return
a blank UniquePtr<CxxString>.
If all you need is a reference to a CxxString, you can alternatively use
cxx::let_cxx_string.