Search code examples
crustffi

Generate opaque pointer in C using rusty-cheddar


I'm trying to generate C header file for a library written in Rust using the rusty-cheddar crate.

Here is the definition and implementation of the struct in Rust:

pub struct AccountDatabase {
    money: HashMap<String, u32>,
}

impl AccountDatabase {
    fn new() -> AccountDatabase {
        AccountDatabase {
            money: HashMap::new(),
        }
    }
}

If I place #[repr(C)] before the struct, rusty-cheddar generates the following declaration of the struct in C

typedef struct AccountDatabase {
    HashMap money;
} AccountDatabase;

The HashMap is not known to C, therefore I'd like for the struct to be declared as an opaque pointer.


Solution

  • The solution is specified right on the readme file:

    To define an opaque struct you must define a public newtype which is marked as #[repr(C)].

    Thus:

    struct AccountDatabase {
        money: HashMap<String, u32>,
    }
    
    impl AccountDatabase {
        fn new() -> AccountDatabase {
            AccountDatabase {
                money: HashMap::new()
            }
        }
    }
    
    #[repr(C)]
    pub struct Crate_AccountDatabase(AccountDatabase);
    

    (or with some other struct naming of your choice)