Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Get function pointer from high-level FnPtrX #35

Open
chachi opened this issue Nov 20, 2021 · 4 comments
Open

Get function pointer from high-level FnPtrX #35

chachi opened this issue Nov 20, 2021 · 4 comments

Comments

@chachi
Copy link

chachi commented Nov 20, 2021

The soundness fixes of #27 are great, but now I don't see an obvious means of passing the FnPtrX struct across a C API as an extern "C" fn pointer directly as before. The func member is private so what would the correct means of getting that pointer be?

@yorickpeterse
Copy link
Collaborator

@chachi See #34 regarding issues with the high interface. With those issues in mind, I don't want to change the API; rather I'd remove it entirely. I'm not sure what you're using libffi for, but you may be better off using either the mid or low API 😃

@chachi
Copy link
Author

chachi commented Nov 21, 2021

That's reasonable but the high-level API is really nice for minimal boilerplate passing of a Rust closure as a callback to a C API. It does indeed require some careful lifetime management to make sure things passed to C are scoped correctly and exist for the right lifetimes, but a sprinkling of unsafe seems like it'd get that point across well.

Overall I'm a huge fan of the magic the high module gives, with the understanding that it's not a totally guaranteed safe API on its own when extracting a code_ptr

@Monadic-Cat
Copy link
Contributor

Monadic-Cat commented Nov 23, 2021

To answer the question:

The func member is private so what would the correct means of getting that pointer be?

It is valid to both transmute a FnPtrX to the corresponding extern "C" fn pointer, and to use it in place of the extern "C" fn pointer type in an FFI declaration, as it is a #[repr(transparent)] struct containing only that and the lifetime carrying PhantomData. (That is, it's ABI compatible with the wrapped fn pointer.)

Edit: Please read issue #34 if you're planning on using the high interface, as lifetime erasure is not the only thing to think about here.

@joshburkart
Copy link

joshburkart commented Mar 3, 2022

@Monadic-Cat Any chance you could provide an example? I'm unable to figure out how to convert your advice into code...

Edit: std::mem::transmute was what I needed. Nevermind!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants