Reputation: 1
I have a matrix in the form of an array in C++ and would like to pass it to a shared library function written in Rust. I have something like this
#![crate_type = "dylib"]
extern crate libc;
use libc::c_void;
extern crate nalgebra as na;
use na::DMatrix2;
#[no_mangle]
pub extern "C" fn rust_fn(p_data: *const c_void, sizex: usize, sizey: usize) {
let matrix = DMatrix2::from_row_vector(sizey, sizex, p_data);
// Do something usefull with the matrix
}
This doesn't compile since I pass a c_void
to from_row_vector()
.
How can I do this right?
The matrix is an array of doubles, but I'm trying to keep the interface generic so I can also call the functions from e.g. Python.
I don't want to free the matrix when returning from the function (I want to borrow, not own the matrix).
Upvotes: 0
Views: 270
Reputation: 31233
You can use std::slice::from_raw_parts
to obtain a slice:
let slice = std::slice::from_raw_parts(p_data, sizex*sizey);
To make sure that the pointer types match up, you can either change p_data
's type in the argument list to *const N
where N
is the type you use in the matrix, or use a cast like p_data as *const N
.
Upvotes: 1