Yet another post about passing pointers to pointers from Rust computer language to C computer language

Following, is yet another amateurish example of computer program code that allows one to write a computer program in the Rust language, and then call a function in the C computer language, containing an object passed between them known as ‘pointer to pointer to character’, or **char as they say in C. This is also sometimes called an “array of pointers”. The purpose of this example is to help future me remember the syntax.

extern "C" {
        fn mainr(argc:i32,argv:*const *const std::os::raw::c_char)->i32;
}

fn main() {
        println!("begin");
        let arg1 = std::ffi::CString::new("/dev/input/js0").unwrap();
        let arg2 = std::ffi::CString::new("--help").unwrap();
        let argv = [arg1.as_ptr(),arg2.as_ptr()];
        unsafe{
                mainr(2,argv.as_ptr());
        }
        println!("end");
}

Over on the C side we have this:

int mainr(int argc, char **argv) {
   //do stuff
}

This was based on a few hours reading, especially https://codeseekah.com/2015/01/25/rusts-osargs-to-cs-argv/

How does it work? Basically, it uses Rust’s “CString” code of Rust’s “Foreign Function Interface” module. Then, it creates what Rust calls a ‘raw pointer’ to the CString’s data.

Then it creates an array of raw pointers. That allows us to slip into the C world, where a **char is pretty much the same as *char[], in other words, in C a pointer to pointer, is a similar enough thing as an array of pointers that you can pass one as the other.

Thanks for reading, future self

Advertisements