Pass a C array to a Rust function

前端 未结 2 1937
-上瘾入骨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.

    0 讨论(0)
  • 2020-12-07 03:55

    @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]
    }
    
    0 讨论(0)
提交回复
热议问题