使用运行时定义的维度将数组从C传递到Rust
我试图通过C将矩阵从R传递到Rust。如果我在Rust函数签名中硬编码数组维度,我可以传递二维数组。有没有一种方法可以通过传递指向数组的指针以及行数和列数来动态执行此操作 我的C代码:使用运行时定义的维度将数组从C传递到Rust,c,arrays,r,rust,C,Arrays,R,Rust,我试图通过C将矩阵从R传递到Rust。如果我在Rust函数签名中硬编码数组维度,我可以传递二维数组。有没有一种方法可以通过传递指向数组的指针以及行数和列数来动态执行此操作 我的C代码: #include "Rinternals.h" #include "R.h" #include <stdint.h> void test1(double* matrix); void test2(double* matrix, int32_t nrow, int32_t ncol); SEXP
#include "Rinternals.h"
#include "R.h"
#include <stdint.h>
void test1(double* matrix);
void test2(double* matrix, int32_t nrow, int32_t ncol);
SEXP pass_matrix_to_rust(SEXP mat, SEXP nrow, SEXP ncol) {
// store nrows and ncols into integers
int32_t rows = *INTEGER(nrow);
int32_t cols = *INTEGER(ncol);
// store pointer to matrix of doubles
double *matrix = REAL(mat);
test1(matrix); // hard coded version
test2(matrix, rows, cols);
return R_NilValue;
}
这是我的建议,假设这是按主要顺序排列的 C代码:
void test2(双*矩阵,int32\u t nrow,int32\u t ncol);
防锈代码:
// This function works but I have to specify the size at compile time
#[no_mangle]
pub extern fn test1(value: *const [[f64; 10]; 10]) {
let matrix = unsafe{*value};
println!("{:?}", matrix);
}
// this function doesn't compile
#[no_mangle]
pub extern fn test2(value: *const f64, nrow: i32, ncol: i32) {
let matrix: [[f64; nrow]; ncol] = unsafe{*value};
println!("{:?}", matrix);
}
// rustc output:
rustc glue.rs
glue.rs:30:29: 30:33 error: no type for local variable 161
glue.rs:30 let matrix: [[f64; nrow]; ncol] = unsafe{*value};
^~~~
glue.rs:30:22: 30:26 error: no type for local variable 158
glue.rs:30 let matrix: [[f64; nrow]; ncol] = unsafe{*value};
^~~~
use std::slice;
#[no_mangle]
pub extern fn test2(pointer: *const f64, nrow: i32, ncol: i32) {
let mut rows: Vec<&[f64]> = Vec::new();
for i in 0..nrow as usize {
rows.push(unsafe {
slice::from_raw_parts(
pointer.offset(i as isize * ncol as isize),
ncol as usize
)
});
}
let matrix: &[&[f64]] = &rows[..];
println!("{:#?}", matrix);
}
使用std::slice;
#[没有损坏]
发布外部fn test2(指针:*常量f64,nrow:i32,ncol:i32){
让mut行:Vec=Vec::new();
对于0..n中的i,请使用{
行。推(不安全){
切片::来自原始零件(
指针偏移量(i为isize*ncol为isize),
使用ncol
)
});
}
让矩阵:&[&[f64]]=&行[…];
println!(“{:?}”,矩阵);
}
Rust在std中没有跨步切片。您需要手动包装它或获得一个库。数组具有编译时长度,这是它们的核心部分之一。你的问题与外国金融机构或外国金融机构无关;您无法创建具有动态长度的数组。这应该是,或的副本“编译时维度未知的矩阵”。@ArtemGr我感觉DMat
将更难跨越FFI边界:-)任何泛型类型的东西。您可能应该看看这一点,它允许使用类型为T的指针和元素数创建切片。