#Getting rust-bindgen to generate PhantomData<&'a T> into a struct

6 messages · Page 1 of 1 (latest)

ruby badge
#

I have a C library which uses a type which is basically a &str:

#[repr(C)]
struct ConstStr {
    ptr: *const u8,
    len: usize,
}

This is what rust-bindgen currently generates for me, can I somehow get it to generate this instead? If so how?

#[repr(C)]
struct ConstStr<'a> {
    ptr: *const u8,
    len: usize,
  _phantom: PhantomData<&' a str>, 
}

This will prevent me from accidentally keeping a ConstStr passed it's lifetime 🙂

blazing basalt
#

it would prob be better to add lifetimes only in the rust side

ruby badge
#

I would've hoped I can do this via their builder pattern in build.rs, I don't want to manually add them on the rust side because this means, either:

  1. I wrap the raw type with a type with a lifetime, this needs to be unwrapped when FFI is called (when unwrapped its on you to not store it elsewhere too, as there are no lifetimes here)
  2. I modify rust-bindgen's output / write the type myself - this means there's no automatic checking and changes if the C header will change
earnest burrow
# ruby badge I would've hoped I can do this via their builder pattern in build.rs, I don't wa...

i suppose you could write a custom attribute macro that modifies the signature. i'd suggest you write something like

// transparent repr ensures that the layout always matches the original type as generated by bindgen
#[repr(transparent)]
struct MyConstStr<'a> {
    inner: ConstStr,
    _phantom: PhantomData<&'a ()>,
}

and then you can call bindgen::Builder::parse_callbacks with a type that implements bindgen::callbacks::ParseCallbacks providing a ParseCallbacks::add_attributes implementation that decorates any relevant functions with an attribute macro that translates instances of ConstStr in argument position to MyConstStr<'_>