Search code examples
crustffi

Is it possible to pass arrays from Rust to C?


I have a very basic Rust function that compiles fine:

use std;
use std::ffi::CString;
use std::os::raw::c_char;

#[no_mangle]
pub extern "C" fn string_from_rust() -> [*const c_char; 2] {
    let s = CString::new("Hello").unwrap();
    let t = CString::new("World").unwrap();
    let p = s.as_ptr();
    let w = t.as_ptr();
    std::mem::forget(s);
    std::mem::forget(t);

    [p, w]
}

In my C header file I inculde

#include <stdint.h>
extern char * string_from_rust();

string_from_rust() only returns "Hello", so I am seemingly doing something wrong, presumably in C, that is allowing only the first element of the Rust array to be passed to C.


Solution

  • The C ABI does not have a concept of "returning an array". You should allocate a Vec<*const c_char> and return it, defining the function on the C side as extern char** string_from_rust().

    Alternatively, since you are returning two pointers, use a #[repr(C)] struct with two members instead of array.