C bindgen generating wrong code

Hi guys, I'm facing some problem in C bindgen code generation

In c bindgen I have one file called cpp_header/wrapper.cpp

Contains

int call_external_c_fn(struct Employee *emp);

After running the bindgen.

It is generating o/p file bindings.rs containing

extern "C"
{
pub fn call_external_c_fn(emp: *mut [u8;0usize])
}

Why it is giving this thing array of size 0 ???
Any solution ?

Probably because the struct is an incomplete type (only forward-declared).

1 Like

correct

no, quite the opposite, because there's no declaration at all. if a struct has only a forward declaration, bindgen will generate a "newtype" struct for it, something like:

// C/C++: struct Employee;
// generated rust:
#[repr(C)]
struct  Employee {
    __opaque: [u8; 0]
}

if however, the struct has an "empty" definition, bindgen will generate a byte-sized struct, I guess because C++ doesn't allow zero-sized type (except when you inherit an "empty" base class, the base type takes zero space)

// C/C++: struct Employee {};
// generated rust:
#[repr(C)]
struct  Employee {
    __address: u8,
}

that's my experience with bindgen anyway.

Note that this would be different from an only forward-declared struct; I was referring to something like struct Employee; – note the lack of braces. Those have an unknown size (and field offsets), much like Rust's DSTs, so bindgen can't really do anything meaningful about them (nor can a C compiler, in fact).