32 releases

0.5.9 Aug 16, 2023
0.5.8 Mar 30, 2023
0.5.7 Apr 29, 2022
0.5.6 Dec 29, 2020
0.0.12 Nov 19, 2015

#12 in FFI

Download history 77640/week @ 2024-07-01 91128/week @ 2024-07-08 85582/week @ 2024-07-15 91037/week @ 2024-07-22 77887/week @ 2024-07-29 90522/week @ 2024-08-05 85212/week @ 2024-08-12 99106/week @ 2024-08-19 95173/week @ 2024-08-26 78117/week @ 2024-09-02 86210/week @ 2024-09-09 66181/week @ 2024-09-16 68344/week @ 2024-09-23 62746/week @ 2024-09-30 63706/week @ 2024-10-07 55039/week @ 2024-10-14

252,960 downloads per month
Used in 265 crates (40 directly)

MIT/Apache

22KB
175 lines

rust-cpp - Embed C++ code directly in Rust

Documentation

Overview

rust-cpp is a build tool & macro which enables you to write C++ code inline in your rust code.

let name = std::ffi::CString::new("World").unwrap();
let name_ptr = name.as_ptr();
let r = unsafe {
    cpp!([name_ptr as "const char *"] -> u32 as "int32_t" {
        std::cout << "Hello, " << name_ptr << std::endl;
        return 42;
    })
};
assert_eq!(r, 42)

The crate also help to expose some C++ class to Rust by automatically implementing trait such as Drop, Clone (if the C++ type can be copied), and others

cpp_class!{
    #[derive(PartialEq)]
    unsafe struct MyClass as "std::unique_ptr<MyClass>"
}

Usage

For usage information and in-depth documentation, see the cpp crate module level documentation.

Differences with the cxx crate

This crate allows to write C++ code "inline" within your Rust functions, while with the cxx crate, you have to write a bit of boiler plate to have calls to functions declared in a different .cpp file.

Having C++ code inline might be helpful when trying to call to a C++ library and that one may wish to make plenty of call to small snippets. It can otherwise be fastidious to write and maintain the boiler plate for many small functions in different places.

These crate can also be used in together. The cxx crate offer some useful types such as CxxString that can also be used with this crate.

The cxx bridge does more type checking which can avoid some classes of errors. While this crate can only check for equal size and alignment.

Dependencies

~0.8–1.5MB
~28K SLoC