Pass a C array to a Rust function

前端 未结 2 1948
-上瘾入骨i
-上瘾入骨i 2020-12-07 03:13

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

2条回答
  •  盖世英雄少女心
    2020-12-07 03:50

    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.

提交回复
热议问题