How to use boolean types in dart FFI?

Viewed 848

I'm trying to use Dart FFIs with Rust. But I can't find any mention/documentation/example on how to use c compatible booleans in FFI. Even the primitives example from Dart official documentation didn't mention about booleans. Is it impossible to use booleans in FFI? If not, how can I approach correctly to use them?

2 Answers

I just found out that the FFI library of Dart doesn't support the boolean types yet, (or they won't I'm not sure). But since Rust's bool type is the same size as C's _Bool type, we can just use bool in Rust and pass Int32 as FFI type in Dart.

0 will become false, and 1 for true. I think it's the same result as converting an i32 to bool in Rust.

Rust implementation,

pub extern "C" fn some_function(arg: bool) {}

and type definition in Dart,

typedef some_function = ffi.Void Function(ffi.Int32);

Just to complement the accepted answer (can't comment yet), despite it works by mangling bool values into ints, the other way around caused issues in my case.

pub extern "C" fn some_function() -> bool

in Dart

typedef some_function = ffi.Int32 Function();

To convert this to a bool I had to do a bitmask with 1 in order to get only the first bit and then see if it was equal to zero.

I'm not sure if I'm reading invalid memory or if it is just not cleared before.

Observed in Dart 2.10.4

Edit

As seen in the Dart SDK itself, they map boolean values to Int8 types.

Related