Passing Rust vector to C++ function using cpp crate

Viewed 150

I am using the cpp crate (https://crates.io/crates/cpp) to run some C++ code from inside Rust. How can I make a vector, that is known to the Rust code available inside the C++ code?

First I tried something like this:

cpp::cpp!{{
    #include <iostream>
    #include <vector>
}}

fn call_some_cpp_stuff(mat: &Vec<f64>, n: usize){
    let n = n as u32;
    unsafe{
        cpp::cpp!([mat as "std::vector", n as "uint32_t"]{
            std::cout << mat[n-1] << std::endl;
        });
    };
}

Which results in the following error:

error[E0512]: cannot transmute between types of different sizes, or dependently-sized types
   --> src/numerics.rs:248:20
    |
248 |         cpp::cpp!([mat as "std::vector<double>", n as "uint32_t"]{
    |                    ^^^
    |
    = note: source type: `&Vec<f64>` (64 bits)
    = note: target type: `[u8; 24]` (192 bits)
    = note: this error originates in the macro `__cpp_closure_impl` (in Nightly builds, run with -Z macro-backtrace for more info)

For more information about this error, try `rustc --explain E0512`.
error: could not compile `rust_dse` due to previous error

When trying to use a pointer instead of a std::vector like this:

cpp::cpp!{{
    #include <iostream>
    #include <vector>
}}

fn call_some_cpp_stuff(mat: &Vec<f64>, n: usize){
    let n = n as u32;
    unsafe{
        cpp::cpp!([mat as "const double *", n as "uint32_t"]{
            std::cout << mat[n-1] << std::endl;
        });
    };
}

It compiles, but I get a segmentation fault when trying to access anything but the 0th element of mat inside the C++ code, even when I am 100% sure, that it does have more than 1 element.

Any ideas on how to achiev this?

1 Answers

If all you want to do is read the contents of the Rust Vec without mutating, you need to use as_ptr:

cpp::cpp!{{
    #include <iostream>
    #include <vector>
}}

fn call_some_cpp_stuff(mat: &Vec<f64>, n: usize){
    let n = n as u32;
    let mat = mat.as_ptr();
    unsafe{
        cpp::cpp!([mat as "const double *", n as "uint32_t"]{
            std::cout << mat[n-1] << std::endl;
        });
    };
}
Related