Skip to content

Commit b3d532f

Browse files
committed
explain the empty type better, and explain to NOT use enums
1 parent 5b45a89 commit b3d532f

File tree

1 file changed

+11
-2
lines changed

1 file changed

+11
-2
lines changed

src/ffi.md

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -751,8 +751,17 @@ extern "C" {
751751
```
752752

753753
By including a private field and no constructor,
754-
we create an opaque type that we can’t instantiate outside of this module.
755-
An empty array is both zero-size and compatible with `#[repr(C)]`.
754+
we create an opaque type that we can't instantiate outside of this module.
755+
(A struct with no field could be instantiated by anyone.)
756+
We also want to use this type in FFI, so we have to add `#[repr(C)]`.
757+
And to avoid warning around using `()` in FFI, we instead use an empty array,
758+
which works just as well as an empty type but is FFI-compatible.
759+
756760
But because our `Foo` and `Bar` types are
757761
different, we’ll get type safety between the two of them, so we cannot
758762
accidentally pass a pointer to `Foo` to `bar()`.
763+
764+
Notice that it is a really bad idea to use an empty enum as FFI type.
765+
The compiler relies on empty enums being uninhabited, so handling values of type
766+
`&Empty` is a huge footgun and can lead to buggy program behavior (by triggering
767+
undefined behavior).

0 commit comments

Comments
 (0)