rustcxx: Using C++ from Rust made easy

Related tags

Command-line rustcxx
Overview

rustcxx: Using C++ from Rust made easy

rustcxx is a tool allowing C++ to be used from a Rust project easily. It works by allowing snippets of C++ to be included within a Rust function, and vice-versa.

Example

#![plugin(rustcxx_plugin)]

cxx_inline! {
    #include <stdint.h>
    uint32_t square_it(uint32_t x) {
        return rust![(x: u32) -> u32 {
            println!("Rust: Squaring {}", x);
            x * x
        }];
    }
}

let x: u32 = 5;
let square = unsafe { cxx![(x: u32) -> u32 {
    std::cout << "C++: Squaring " << x << std::endl;
    square_it(x)
}] };

See the provided example for more details.

Usage

rustcxx requires a nightly version of the Rust compiler.

Add to your Cargo.toml:

[package]
build = "build.rs"

[dependencies.rustcxx_plugin]
git = "https://github.com/google/rustcxx"
branch = "unstable"

[build-dependencies.rustcxx_codegen]
git = "https://github.com/google/rustcxx"
branch = "unstable"

and create a build.rs file containing the following:

extern crate rustcxx_codegen;

fn main() {
    rustcxx_codegen::build("src/main.rs");
}

Authors

The main author is Paul Liétar.

Contributions

We gladly accept contributions via GitHub pull requests, as long as the author has signed the Google Contributor License. Please see CONTRIBUTING.md for more details.

Disclaimer

This is not an official Google product (experimental or otherwise), it is just code that happens to be owned by Google.

You might also like...
A simple made in Rust crack, automatic for Winrar, activated from shared virtual memory, for studies.
A simple made in Rust crack, automatic for Winrar, activated from shared virtual memory, for studies.

Simple Winrar Crack in Rust What does it do ? A simple project that allows you to modify the license check used by WinRaR, "RegKey" from virtual memor

Gamehacking.Academy but made with Rust

Just the programs etc. i made following the lessons on gamehacking.academy but instead of using the cpp i tried translating it to Rust

👀Little program I made in 🦀Rust that reminds me every 20 minutes to look away from my computer 🖥screen.
👀Little program I made in 🦀Rust that reminds me every 20 minutes to look away from my computer 🖥screen.

👀 eye break Little program I made in 🦀 Rust that reminds me every 20 minutes to look away from my computer 🖥 screen. I stay way too long on the com

A "Shell" made in Rust

Ironclad-shell A "shell" command interpreter made in rust. First things first This is my first time posting to reddit and my first time using rust (al

A simple AUR helper made in Rust.
A simple AUR helper made in Rust.

AURme A simple AUR helper made in Rust. Description AURme is a simple and minimalist tool made to help users install, update and maintain packages fro

awesome fullstack rust web framework, made by axum & shaku & yew

Awesome Rust Full Stack Web Framework With Axum && shaku && yew, this repository represents how can we construct new web server used by rust. Still in

SquidVM is a VM made in Rust implementing a Stack-based machine.

What is SquidVM? _____ _ ___ ____ __ / ____| (_) | \ \ / / \/ | | (___ __ _ _ _ _ __| |\ \ / /| \ /

Simple joke randomizer from bash.org.pl made as CLI Tool in Rust.

RBashOrg Simple joke randomizer from bash.org.pl made as CLI Tool in Rust. Description Main motivation of this project was to learn basic concepts abo

A simple TUI password manager made in Rust.

IronKey IronKey is a Terminal User Interface (TUI) based password generator written in Rust. It leverages the power of Rust's performance and safety f

Comments
  • Compile error

    Compile error

    I cloned your Repository and tried to compile the example but i got this:

    [jan@helium example]$ cargo build
        Updating registry `https://github.com/rust-lang/crates.io-index`
       Compiling rustcxx_common v0.1.0 (file:///home/jan/Uni/Bachelorarbeit/Programme/rustcxx/common)
       Compiling gcc v0.3.54
    error[E0432]: unresolved import `syntax::abi`
      --> common/lib.rs:27:13
       |
    27 | use syntax::abi::Abi;
       |             ^^^ Could not find `abi` in `syntax`
    
    error[E0432]: unresolved import `syntax::codemap::spanned`
      --> common/lib.rs:29:61
       |
    29 | use syntax::codemap::{Span, Spanned, dummy_spanned, respan, spanned, DUMMY_SP};
       |                                                             ^^^^^^^ no `spanned` in `codemap`. Did you mean to use `Spanned`?
    
    error[E0432]: unresolved import `syntax::parse::common`
      --> common/lib.rs:35:20
       |
    35 | use syntax::parse::common::SeqSep;
       |                    ^^^^^^ Could not find `common` in `parse`
    
    error[E0412]: cannot find type `SpannedIdent` in module `ast`
      --> common/lib.rs:52:40
       |
    52 |                            ident: ast::SpannedIdent) -> PResult<'a, Self::ArgValue>;
       |                                        ^^^^^^^^^^^^ not found in `ast`
    
    error[E0412]: cannot find type `SpannedIdent` in module `ast`
      --> common/lib.rs:68:40
       |
    68 |                            ident: ast::SpannedIdent) -> PResult<'a, Self::ArgValue> {
       |                                        ^^^^^^^^^^^^ not found in `ast`
    
    error[E0412]: cannot find type `SpannedIdent` in module `ast`
      --> common/lib.rs:97:40
       |
    97 |                            ident: ast::SpannedIdent) -> PResult<'a, Self::ArgValue> {
       |                                        ^^^^^^^^^^^^ not found in `ast`
    
    error[E0412]: cannot find type `SpannedIdent` in module `ast`
       --> common/lib.rs:212:21
        |
    212 |     pub ident: ast::SpannedIdent,
        |                     ^^^^^^^^^^^^ not found in `ast`
    
    error[E0425]: cannot find function `intern` in module `token`
       --> common/lib.rs:342:57
        |
    342 |         let no_mangle = ecx.meta_word(self.span, token::intern("no_mangle").as_str());
        |                                                         ^^^^^^ not found in `token`
    
    error[E0425]: cannot find function `intern` in module `token`
       --> common/lib.rs:348:20
        |
    348 |             token::intern("deny").as_str(),
        |                    ^^^^^^ not found in `token`
    
    error[E0425]: cannot find function `intern` in module `token`
       --> common/lib.rs:349:60
        |
    349 |             vec![ecx.meta_list_item_word(self.span, token::intern("private_no_mangle_fns").as_str())]);
        |                                                            ^^^^^^ not found in `token`
    
    warning: use of deprecated item 'std::hash::SipHasher': use `std::collections::hash_map::DefaultHasher` instead
      --> common/lib.rs:24:17
       |
    24 | use std::hash::{SipHasher, Hash, Hasher};
       |                 ^^^^^^^^^
       |
       = note: #[warn(deprecated)] on by default
    
    warning: use of deprecated item 'std::hash::SipHasher': use `std::collections::hash_map::DefaultHasher` instead
       --> common/lib.rs:135:30
        |
    135 |             let mut hasher = SipHasher::new();
        |                              ^^^^^^^^^^^^^^
    
    error[E0624]: method `check` is private
      --> common/lib.rs:71:27
       |
    71 |             while !parser.check(&token::Comma) &&
       |                           ^^^^^
    
    error[E0624]: method `check` is private
      --> common/lib.rs:72:27
       |
    72 |                   !parser.check(&token::CloseDelim(token::Paren)) {
       |                           ^^^^^
    
    error[E0624]: method `parse_token_tree` is private
      --> common/lib.rs:73:41
       |
    73 |                 tokens.push(try!(parser.parse_token_tree()));
       |                                         ^^^^^^^^^^^^^^^^
    
    error[E0624]: method `parse_token_tree` is private
      --> common/lib.rs:92:29
       |
    92 |             |parser| parser.parse_token_tree())
       |                             ^^^^^^^^^^^^^^^^
    
    error[E0624]: method `check` is private
       --> common/lib.rs:120:30
        |
    120 |         let args = if parser.check(&token::OpenDelim(token::Paren)) {
        |                              ^^^^^
    
    error[E0624]: method `check` is private
       --> common/lib.rs:126:50
        |
    126 |         let ret_ty = if args.is_some() && parser.check(&token::RArrow) {
        |                                                  ^^^^^
    
    warning: use of deprecated item 'std::hash::SipHasher::new': use `std::collections::hash_map::DefaultHasher` instead
       --> common/lib.rs:135:30
        |
    135 |             let mut hasher = SipHasher::new();
        |                              ^^^^^^^^^^^^^^
    
    error[E0624]: method `parse_unspanned_seq` is private
       --> common/lib.rs:153:16
        |
    153 |         parser.parse_unspanned_seq(
        |                ^^^^^^^^^^^^^^^^^^^
    
    error[E0599]: no associated item named `Inherited` found for type `syntax::codemap::Spanned<syntax::ast::VisibilityKind>` in the current scope
       --> common/lib.rs:189:18
        |
    189 |             vis: ast::Visibility::Inherited,
        |                  ^^^^^^^^^^^^^^^^^^^^^^^^^^ associated item not found in `syntax::codemap::Spanned<syntax::ast::VisibilityKind>`
    
    error[E0615]: attempted to take value of method `lo` on type `syntax::codemap::Span`
       --> common/lib.rs:221:34
        |
    221 |             let lo = parser.span.lo;
        |                                  ^^
        |
        = help: maybe a `()` to call it is missing?
    
    error[E0615]: attempted to take value of method `lo` on type `syntax::codemap::Span`
       --> common/lib.rs:223:34
        |
    223 |             let hi = parser.span.lo;
        |                                  ^^
        |
        = help: maybe a `()` to call it is missing?
    
    error[E0061]: this function takes 4 parameters but 6 parameters were supplied
       --> common/lib.rs:356:23
        |
    356 |           let fn_item = ast::ItemKind::Fn(
        |  _______________________^
    357 | |             decl, ast::Unsafety::Unsafe, dummy_spanned(ast::Constness::NotConst),
    358 | |             Abi::C, ast::Generics::default(), self.body.clone());
        | |________________________________________________________________^ expected 4 parameters
    
    error[E0599]: no associated item named `Public` found for type `syntax::codemap::Spanned<syntax::ast::VisibilityKind>` in the current scope
       --> common/lib.rs:365:18
        |
    365 |             vis: ast::Visibility::Public,
        |                  ^^^^^^^^^^^^^^^^^^^^^^^ associated item not found in `syntax::codemap::Spanned<syntax::ast::VisibilityKind>`
    
    error[E0063]: missing field `tokens` in initializer of `syntax::ast::Item`
       --> common/lib.rs:360:11
        |
    360 |         P(ast::Item {
        |           ^^^^^^^^^ missing `tokens`
    
    error[E0023]: this pattern has 1 field, but the corresponding tuple variant has 2 fields
       --> common/lib.rs:382:40
        |
    382 |             (Some(&TokenTree::Token(_, token::Ident(ident))),
        |                                        ^^^^^^^^^^^^^^^^^^^ expected 2 fields, found 1
    
    error[E0599]: no variant named `Sequence` found for type `syntax::tokenstream::TokenTree` in the current scope
       --> common/lib.rs:401:20
        |
    401 |             (Some(&TokenTree::Sequence(..)), _, _) => unimplemented!(),
        |                    ^^^^^^^^^^^^^^^^^^^^^^^ variant not found in `syntax::tokenstream::TokenTree`
    
    error[E0308]: mismatched types
       --> common/lib.rs:387:39
        |
    387 |                 result.extend(f(span, &contents.tts));
        |                                       ^^^^^^^^^^^^^ expected slice, found struct `syntax::tokenstream::ThinTokenStream`
        |
        = note: expected type `&[syntax::tokenstream::TokenTree]`
                   found type `&syntax::tokenstream::ThinTokenStream`
    
    error[E0609]: no field `open_span` on type `&syntax::tokenstream::Delimited`
       --> common/lib.rs:392:45
        |
    392 |                 result.push(respan(contents.open_span, token_to_string(&contents.open_token())));
        |                                             ^^^^^^^^^
    
    error[E0308]: mismatched types
       --> common/lib.rs:393:48
        |
    393 |                 result.extend(parse_rust_macro(&contents.tts, f));
        |                                                ^^^^^^^^^^^^^ expected slice, found struct `syntax::tokenstream::ThinTokenStream`
        |
        = note: expected type `&[syntax::tokenstream::TokenTree]`
                   found type `&syntax::tokenstream::ThinTokenStream`
    
    error[E0609]: no field `close_span` on type `&syntax::tokenstream::Delimited`
       --> common/lib.rs:394:45
        |
    394 |                 result.push(respan(contents.close_span, token_to_string(&contents.close_token())));
        |                                             ^^^^^^^^^^
    
    error[E0599]: no variant named `Sequence` found for type `syntax::tokenstream::TokenTree` in the current scope
       --> common/lib.rs:430:14
        |
    430 |             &TokenTree::Sequence(..) => unimplemented!()
        |              ^^^^^^^^^^^^^^^^^^^^^^^ variant not found in `syntax::tokenstream::TokenTree`
    
    error[E0609]: no field `open_span` on type `&syntax::tokenstream::Delimited`
       --> common/lib.rs:422:45
        |
    422 |                 let open = respan(delimited.open_span, token_to_string(&delimited.open_token()));
        |                                             ^^^^^^^^^
    
    error[E0609]: no field `close_span` on type `&syntax::tokenstream::Delimited`
       --> common/lib.rs:423:46
        |
    423 |                 let close = respan(delimited.close_span, token_to_string(&delimited.close_token()));
        |                                              ^^^^^^^^^^
    
    error[E0308]: mismatched types
       --> common/lib.rs:426:40
        |
    426 |                     .chain(flatten_tts(&delimited.tts))
        |                                        ^^^^^^^^^^^^^^ expected slice, found struct `syntax::tokenstream::ThinTokenStream`
        |
        = note: expected type `&[syntax::tokenstream::TokenTree]`
                   found type `&syntax::tokenstream::ThinTokenStream`
    
    error[E0615]: attempted to take value of method `lo` on type `syntax::codemap::Span`
       --> common/lib.rs:440:57
        |
    440 |     let mut last_pos = codemap.lookup_char_pos(DUMMY_SP.lo);
        |                                                         ^^
        |
        = help: maybe a `()` to call it is missing?
    
    error[E0615]: attempted to take value of method `lo` on type `syntax::codemap::Span`
       --> common/lib.rs:446:58
        |
    446 |             let pos = codemap.lookup_char_pos(token.span.lo);
        |                                                          ^^
        |
        = help: maybe a `()` to call it is missing?
    
    error[E0615]: attempted to take value of method `lo` on type `syntax::codemap::Span`
       --> common/lib.rs:475:44
        |
    475 |     let pos = codemap.lookup_char_pos(span.lo);
        |                                            ^^
        |
        = help: maybe a `()` to call it is missing?
    
    error[E0618]: expected function, found enum variant `Err`
      --> common/types.rs:38:13
       |
    38 |             Err(handler.struct_span_err(ty.span, &msg))
       |             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ not a function
    help: `Err` is a unit variant, you need to write it without the parenthesis
       |
    38 |             Err
       |
    
    error[E0609]: no field `identifier` on type `&syntax::ast::PathSegment`
      --> common/types.rs:63:40
       |
    63 |             let name : &str = &segment.identifier.name.as_str();
       |                                        ^^^^^^^^^^
    
    error[E0609]: no field `identifier` on type `&syntax::ast::PathSegment`
      --> common/types.rs:79:40
       |
    79 |         Some((module, rest)) if module.identifier.name.as_str() == "libc" && rest.len() == 1 => {
       |                                        ^^^^^^^^^^
    
    error[E0609]: no field `identifier` on type `syntax::ast::PathSegment`
      --> common/types.rs:80:40
       |
    80 |             let name : &str = &rest[0].identifier.name.as_str();
       |                                        ^^^^^^^^^^ unknown field
       |
       = note: available fields are: `ident`, `args`
    
    error: aborting due to 40 previous errors
    
    Some errors occurred: E0023, E0061, E0063, E0308, E0412, E0425, E0432, E0599, E0609...
    For more information about an error, try `rustc --explain E0023`.
    error: Could not compile `rustcxx_common`.
    
    To learn more, run the command again with --verbose.
    
    opened by Mateholiker 4
  • The code generator use the statement expression which is not supported in MSVC

    The code generator use the statement expression which is not supported in MSVC

    Currently, rustcxx use the statement expression feature (which is gcc feature) to generate the cxx! code.

    However, It makes us uneasy to use rustcxx with MSVC.

    Do you have a plan to change this?

    opened by harryfei 0
Owner
Google
Google ❤️ Open Source
Google
Easy access of struct fields in strings using different/custom pre/postfix: "Hello, {field}" in rust

Easy access to struct fields in strings ?? add strung to the dependencies in the Cargo.toml: [dependencies] strung = "0.1.3" ?? use/import everything

Dekirisu 2 Sep 19, 2022
Nodium is an easy-to-use data analysis and automation platform built using Rust, designed to be versatile and modular.

Nodium is an easy-to-use data analysis and automation platform built using Rust, designed to be versatile and modular. Nodium aims to provide a user-friendly visual node-based interface for various tasks.

roggen 19 May 2, 2023
Replace an app's icon from a png with a single terminal script. Made with Rust

Replace macOS App Icon Replace an app's icon from a png with a single terminal CLI. Made with Rust

Kunal Bagaria 8 Aug 3, 2022
Simple system monitoring app that runs on terminal. Made purely with Rust.

What is it? RCTOP is a simple WIP system monitoring app that runs purely on terminal and doesn't feature GUI. One can compare it to htop, but more str

Niko Huuskonen 7 Oct 14, 2022
A shell Made in rust 🦀

vsh A Blazingly fast shell made in Rust ?? Why make another shell? Because the current leading rust shell is very opinionated, atleast to me. As it br

null 89 Dec 18, 2022
🌳 A lightning-fast system fetch tool made with Rust.

?? treefetch A lightning-fast minimalist system fetch tool made in Rust. Even faster than neofetch and pfetch. Made to practice my new Rust skills ??

Angelo-F 134 Dec 14, 2022
This repository presents a numbers vizualizer in a polar base. This small project has been entirely made in Rust !

NumbersRepresentation This repository presents a numbers vizualizer in a polar base. This small project has been entirely made in Rust ! This is an id

Lilian 'S3l4h' Schall 3 Apr 12, 2022
A simple CLI I made while practicing rust to easily make QR codes with just one command, all in your terminal.

Welcome to rust-qrcode-cli ?? A CLI I made while practicing rust to easily make QR codes with just one command, all in your terminal. Install git clon

Dhravya Shah 2 Mar 2, 2022
A minecraft clone made in Rust - WIP

unsafe {} A minecraft clone made in Rust. The world is infinite in all three directions. DISCLAIMER: Some textures are stolen from the chisel mod HEAV

Adam Harmansky 5 Jul 18, 2022
collaboration project focusing on rust. Made for fun

Collaboration space for on rust project(s) setup Pull down the repo first then do the following steps cd into lil-devils cargo fetch cargo build cargo

Blake Costa 2 Nov 8, 2022