Is there an idomatic way of dealing with raw pointers generated by bindgen?

Hello, I've been trying to make safe bindings for some C functions using bindgen. I came across this struct which uses an unsafe pointer in its field.

pub struct XVisualInfo {
    pub visual: *mut Visual,
    pub visualid: VisualID,
    // ...

Some of the functions requires this field as an argument. It would've been convenient, if the field was wrapped under a Option<Box<Visual>> or other safer rust alternatives so as to not expose the pointer outside.
Is there anyway reusing the same structure without resorting to re-implement safer version of this?

No, it's not possible. The reason why Bindgen doesn't generate an Option<Box<_>> is because it can't. It doesn't know about the ownership rules of the pointer, since the C type system has no notion of ownership. If bindgen pretended to generate "safe" Rust code, it would in fact be egregiously incorrect. Due to the invalid assumptions of owning/non-owning nature of pointers, such bindings would be riddled with either double-frees or memory leaks.

You'll have to read the documentation of the C library and wrap it manually by obeying its ownership rules. There's no easy (let alone automated) way around that, since this information is not available in machine-readable form in a C program.


This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.