Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass a C array to a Rust function

Tags:

arrays

c

rust

I'm trying to make a Rust dylib and use it from other languages, like C, Python and others. I've successfully called a Rust function taking an i32 argument from Python. Now I'm trying to make a function that takes an array (or a pointer to it, or whatever is necessary to pass a dataset to Rust).

#![crate_type = "dylib"]
#[no_mangle]
pub extern "C" fn rust_multiply(size: i32, arrayPointer: &i32) -> i32 {
    *(arrayPointer)
}

This works as expected. But

#![crate_type = "dylib"]
#[no_mangle]
pub extern "C" fn rust_multiply(size: i32, arrayPointer: &i32) -> i32 {
    *(arrayPointer + 1) // trying to get next element
}

fails with

error[E0614]: type `i32` cannot be dereferenced
 --> src/lib.rs:4:5
  |
4 |     *(arrayPointer + 1) // trying to get next element
  |     ^^^^^^^^^^^^^^^^^^^

Doing this:

pub extern fn rust_multiply(size: i32, array: &[i32]) -> i32

and doing something like array[0] fails with "length = 0" error.

like image 898
aspcartman Avatar asked Mar 21 '15 12:03

aspcartman


1 Answers

You have to make some efforts to provide a pure C API and implement some conversions using unsafe code. Fortunately, it is not so difficult:

extern crate libc;

#[no_mangle]
pub extern "C" fn rust_multiply(
    size: libc::size_t,
    array_pointer: *const libc::uint32_t,
) -> libc::uint32_t {
    internal_rust_multiply(unsafe {
        std::slice::from_raw_parts(array_pointer as *const i32, size as usize)
    }) as libc::uint32_t
}

fn internal_rust_multiply(array: &[i32]) -> i32 {
    assert!(!array.is_empty());
    array[0]
}

There is a good introduction for Rust FFI on the official site.

like image 78
swizard Avatar answered Nov 01 '22 14:11

swizard