Using a C library and running into trouble


#1

I want to use a C library in my Rust code. So far I use bindgen in my build.rs to include the library’s header file in main.rs and I use the GCC crate to compile the library’s binary and link it to the main executable. This works, I think.

I also have a C file which uses the same library and I want to use the library from Rust in a similar way. I started by converting the C code to Rust line by line. Now I got stuck: The original C code (here: https://github.com/medium-endian/crisp/blob/master/cisp/parsing.c) declares a struct mpc_result_t on line 41 and proceeds to call a function which initializes the struct (line 42). On compiling, I am getting ‘use of possibly uninitialized memory’ errors. This is understandable. But how do I initialize the struct so that the C function can write to memory? Rust code (same file as above but in Rust): https://github.com/medium-endian/crisp/blob/master/rusp/src/main.rs relevant parts around line 35.

The main.rs file linked above is messy because I am just trying to get it to compile at the moment. I hope someone will still read through :smiley:


#2

Ok, solved it myself by using Default::default() as struct initialisation.


#3

I can’t see the code (it’s been removed? private?) but if you’re creating a wrapper for a C library, you can make initialization automatic like this:

struct Wrapper {inner: some_c_struct_type;}

impl Wrapper {
    pub fn new() -> Self {
        unsafe { 
            let mut inner = std::mem::uninitialized();
            c_library_init(&mut inner);
            Wrapper {
                inner: inner,
            }
        }
    }
}

// and impl Drop for Wrapper if the library requires deinitialization

This way Rust will be able to use Wrapper::new() that automatically initializes struct using the C library without need to implement Default for C types.


#4

I’m sorry, I deleted a branch without thinking! Fixed the links now.

rust-bindgen automatically generates a default() implementation, actually. But now I am trying to wrap all the C code to rustify it.