使用 cpp crate 将 Rust 向量传递给 C++ 函数

Passing Rust vector to C++ function using cpp crate

我正在使用 cpp crate (https://crates.io/crates/cpp) 来 运行 来自 Rust 内部的一些 C++ 代码。 我怎样才能制作一个矢量,这是 C++ 代码中可用的 Rust 代码已知的?

首先我尝试了这样的事情:

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;
        });
    };
}

这会导致以下错误:

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

当尝试使用指针而不是像这样的 std::vector 时:

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;
        });
    };
}

它可以编译,但是当我尝试访问除 C++ 代码中 mat 的第 0 个元素以外的任何元素时,我会遇到分段错误,即使我 100% 确定它确实有不止 1 个元素.

关于如何实现这一点有什么想法吗?

如果你只想读取 Rust Vec 的内容而不改变,你需要使用 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;
        });
    };
}