Closed
Description
Dart ints are signed 64 bit ints, so they cannot hold the values [2 ^ 63, ..., 2 ^ 64 - 1]
.
We have three options:
- Keep
Uint64
and interpret the bits asInt64
in Dart. - Keep
Uint64
, but throw an error if weload
a value that we cannot represent in Dart. - remove
Uint64
, and writeInt64
in signatures.
Interpret bits differently in Dart
Pointer<Uint64> p = allocate();
p.store(0x7FFFFFFFFFFFFFFF); // 2 ^ 63 - 1
Expect.equals(0x7FFFFFFFFFFFFFFF, p.load<int>());
p.store(-0x8000000000000000); // -2 ^ 63 interpreted as 2 ^ 63
Expect.equals(-0x8000000000000000, p.load<int>());
p.store(-1); // -1 interpreted as 2 ^ 64 - 1
Expect.equals(-1, p.load<int>());
ffi.free(p);
Pro: we can represent the C signatures
Con: interpreting bits differently on load
/store
can be confusing
Throw an error on loading
Pointer<Int64> p = allocate();
p.store(-1);
Expect.equals(-1, p.load<int>());
Pointer<Uint64> p2 = p.cast(); // bits for -1 are now 2 ^ 64 - 1
Expect.throws(() => p2.load<int>());
ffi.free(p);
Pro: explicit that bits are interpreted differently
Con: verbose
Drop Uint64 and use Int64
typedef NativeFunc = Int64 Function(Int64); // for some Uint64 Function(Uint64) in C
int Function(int) f = somePointer.asFunction();
int result = f(-1); // will be interpreted as 2 ^ 64 - 1 by C
Expect.equals(-1, result); // C returing 2 ^ 64 - 1 shows up as -1 in Dart
Con: interpreting bits differently can be confusing
Con 2: signatures of C function in Dart does not correspond to signature in h file