7

I have some code generated by bindgen that has function pointers represented by Option<T>.

pub type SomeFnPointerType = ::std::option::Option<
  unsafe extern "C" fn ( /* .. large number of argument types .. */) 
    -> /* return type */
> ;

I want to store the unwrapped values in a structure. However, there are no type aliases for the inner function pointer types, so how can I define that structure? I cannot refactor the code because it's automatically generated.

I want to do something like this (in C++'ish pseudo code):

struct FunctionTable {
  decltype((None as SomeFnPointerType).unwrap()) unwrappedFn;
  /* ... */
};

or maybe just SomeFnPointerType::T if that is allowed.

Is it possible to achieve that in Rust? If not, the only way I see it is to manually define those types by copy-pasting code from the generated file into a separate handwritten file and keep the types in sync manually.

7

You can define a trait that exposes the T as an associated type.

trait OptionExt {
    type Type;
}

impl<T> OptionExt for Option<T> {
    type Type = T;
}

type MyOption = Option<fn()>;

fn foo(f: <MyOption as OptionExt>::Type) {
    f();
}

fn main() {
    foo(|| {});
}

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.