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

Described opaque type pattern has issues #250

Closed
skade opened this issue Dec 16, 2020 · 1 comment
Closed

Described opaque type pattern has issues #250

skade opened this issue Dec 16, 2020 · 1 comment

Comments

@skade
Copy link
Contributor

skade commented Dec 16, 2020

It was recently pointed out that the current suggestion around representing opaque types in Rust has issues.

https://doc.rust-lang.org/nomicon/ffi.html#representing-opaque-structs

#[repr(C)] pub struct Bar { _private: [u8; 0] }

This type ends up being Send, Sync and Unpin, all properties which might not hold for the type hidden.

A type I came up with @dtolnay and @nvzqz to fix those issues is the following:

#[repr(C)]
pub struct opaque_example {
    // Required for FFI-safe 0-sized type.
    //
    // In the future, this should refer to an extern type.
    // See https://github.com/rust-lang/rust/issues/43467.
    _data: [u8; 0],

    // Required for !Send & !Sync & !Unpin.
    //
    // - `*mut u8` is !Send & !Sync. It must be in `PhantomData` to not
    //   affect alignment.
    //
    // - `PhantomPinned` is !Unpin. It must be in `PhantomData` because
    //   its memory representation is not considered FFI-safe.
    _marker:
        core::marker::PhantomData<(*mut u8, core::marker::PhantomPinned)>,
}

(An implementation can be found here: https://github.com/skade/ffi-opaque/)

For reference, this matches the current behaviour of RFC 1861 extern types: rust-lang/rust#44295 (comment)

@skade skade changed the title Described opaque type has issues Described opaque type pattern has issues Dec 16, 2020
@JohnTitor
Copy link
Member

Makes sense, @skade do you have time to update the docs? If not I'm happy to work on it instead :)

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

2 participants