gpt4 book ai didi

c - 将数组从 C 传递给 Rust,尺寸在运行时定义

转载 作者:太空宇宙 更新时间:2023-11-03 23:46:38 25 4
gpt4 key购买 nike

我正在尝试通过 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 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;
}

我的 Rust 代码:

// 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};
^~~~

最佳答案

这是我的建议,假设这是行优先顺序。

C 代码:

void test2(double* matrix, int32_t nrow, int32_t ncol);

防 rust 代码:

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

关于c - 将数组从 C 传递给 Rust,尺寸在运行时定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30959706/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com