Rust's stability story should apply to bool in FFI

That snippet is not correct (although it will not result in undefined behavior as written - only if banana attempts to read from or write to that parameter). Due to TBAA rules, passing a uint8_t object to a parameter as a _Bool* will result in undefined behavior if the function ever reads or writes from that parameter.

Second, that’s an incorrect assumption of the definition of the C standard - it doesn’t define what happens when you read an object of type uint8_t from a pointer of type _Bool, therefore, it doesn’t need to care about what happens. The valid bit patterns aren’t defined in the C standard, however they are defined by specific platforms. For x86/64 platforms, _Bool is defined as a byte-width object, with value 0 or 1.

What C defines is:

  • Conversion from 0 to _Bool will result in a _Bool with value 0.

  • Conversion from an integer or floating point type that is not equal to 0, to _Bool, will result in a _Bool with value 1.

  • Conversion from a _Bool with value 0, to an integer or floating point type, will result in a 0 value of that type.

  • Conversion from a _Bool with value 1, to an integer or floating point type, will result in a 1 value of that type.

In practice, the code that you’ve written, assuming TBAA is turned off, will only work for x = 0, and x = 1.

5 Likes