Simple cdylib in rust to call from C (using pointers to array)

Hello everyone,

I'm am new to Rust and I am trying to create a simple shared library, which I can call from other places (like C or C++ codes).

I am trying to create a function in my lib.rs file, called rust_function which takes a pointer to an array, adds a value to all the elements of the array, and returns a pointer to the array back. The code I have so far is:

lib.rs:

]
mod tests {
    #[test]
    fn it_works() {
        assert_eq!(2 + 2, 4);
    }
}

#[no_mangle]
pub extern "C" fn rust_function(&mut a: [i32; 2] ) -> &mut [i32; 2] {
    for i in a.iter_mut() {
        *i = *i + 1;
    }
    a
}

code.c:

#include <stdio.h>
#include "rust_function.h"

int main(){
	int a[2] = {1, 2};
	printf("a => [%d, %d]\n", a[0], a[1]);
	
	int b[2];
	b[0] = *rust_function(&a)[0];
	b[1] = *rust_function(&a)[1];
	
	printf("b => [%d, %d]\n", b[0], b[1]);
}

I am not really familiar with c, and as I am new to rust, these codes are probably wrong in many ways. I see the rust compiler is telling me to use a static lifetime, but I haven't figured out how. I would really appreciate it if anyone has any suggestion or resources for further reading and learning!

The correct type is &mut [i32; 2]. It does not go on the parameter name.

I'd recommend reading safer-ffi's guide:

image

Thanks, that solved the problem.

Thank you for the advice. I'll read through it when I find the time.

1 Like