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. No
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.
@swizard's answer gets unsigned integers and converts them to signed integers. The code you probably want is
extern crate libc;
#[no_mangle]
pub extern "C" fn rust_multiply(
size: libc::size_t,
array_pointer: *const libc::int32_t,
) -> libc::int32_t {
internal_rust_multiply(unsafe {
std::slice::from_raw_parts(array_pointer as *const i32, size as usize)
}) as libc::int32_t
}
fn internal_rust_multiply(array: &[i32]) -> i32 {
assert!(!array.is_empty());
array[0]
}