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

Passing Rust vector to C++ function using cpp crate

本文关键字:C++ 函数 向量 cpp-crate Rust 使用      更新时间:2024-09-26

我正在使用cpp机箱(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::向量时:

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个以上的元素,我也会遇到分段错误。

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

如果您只想在不发生变化的情况下读取RustVec的内容,则需要使用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;
});
};
}