我正在撰寫 Rust 函式的 c 系結。Rust 函式采用 3D 切片,其中 2 個維度的大小為 2。本質上它是一段二維線段,其中一條線段由 2 個點表示。
這意味著段具有型別:
segments: [[[f32; 2]; 2]]
現在,因為我從 CI 呼叫它,所以在 FFI 邊界只有一個簡單的f32指標。我的來自 c 的多維陣列采用行優先記憶體順序,據我所知,這與 Rust 所期望的相匹配。所以在道義上我應該可以對銹說:就是那種型別。
我查看了https://doc.rust-lang.org/std/ptr/fn.slice_from_raw_parts.html但我看不出如何處理更復雜的結構。
因此,為了使其非常具體,我希望能夠呼叫foofromfoo_c并且foo應該處理從指標到 3D 切片/陣列結構的轉換。
#[no_mangle]
pub unsafe extern fn foo_c(segments: *f32, n_segments: usize) {
foo(...)
}
fn foo(segments: [[[f32; 2]; 2]]) {
...
}
如果可能的話,我想在不復制任何資料的情況下這樣做。
任何幫助表示贊賞!
uj5u.com熱心網友回復:
首先我認為你打錯了一些字,所以我假設你的代碼是:
#[no_mangle]
// missing `const`
pub unsafe extern fn foo_c(segments: *const f32, n_segments: usize) {
foo(...)
}
// missing `&`
fn foo(segments: &[[[f32; 2]; 2]]) {
...
}
解決辦法是:
#[no_mangle]
pub unsafe extern fn foo_c(segments: *const f32,n_segments: usize) {
// first we cast the pointer to get the slice `T`
// so from a generic `*const f32` to `*const T` where T is `[[f32; 2]; 2]`
let ptr = segments as *const [[f32; 2]; 2];
// we construct the slice using `slice_from_raw_parts`
// after we got the correct pointer.
let segments_slice = std::ptr::slice_from_raw_parts::<[[f32;2];2]>(ptr,n_segments);
// we still have `*const [[f32; 2]; 2]` which we need to convert
// to `&[[f32; 2]; 2]` so we use `&*` (dereference then borrow).
foo(&*segments_slice)
}
fn foo(segments: &[[[f32; 2]; 2]]) {
println!("segments {:?}",segments);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/537272.html
標籤:指针锈防锈绑定
