dart-lang / sdk

The Dart SDK, including the VM, JS and Wasm compilers, analysis, core libraries, and more.
https://dart.dev
BSD 3-Clause "New" or "Revised" License
10.06k stars 1.56k forks source link

[documentation/ffi] Document marshalling/conversion behavior #51648

Open dcharkes opened 1 year ago

dcharkes commented 1 year ago

https://api.dart.dev/stable/2.19.3/dart-ffi/FloatPointer.html https://api.dart.dev/stable/2.19.3/dart-ffi/FloatArray.html

This uses the hardware float<->double conversion on storing on the properties and operators.

If Dart double value is larger than FLT_MAX this can lead to unexpected behavior.

Since the value getter and value setter share documentation, we would need to add this 'setter' documentation on the getter.

https://api.dart.dev/stable/2.19.3/dart-ffi/Uint32Pointer.html

For integers we truncate on setters, this is also not documented.

lrhn commented 1 year ago

I'd say it leads to entirely expected behavior (I can't imagine any other behavior, so I wouldn't expect it). It's just something the user needs to be aware of.

There can also be loss of precision for any double value with more than 24 significant bits (out of the 53 possible).

We could add a toFloat32() method on double, or in dart:typed_data, to allow you to do the conversion early. Since all values of a float-32 can be stored in a float-64, nothing is lost in the other direction. Naive implementation:

extension DoubleToFloat on double {
  static final _floatConverter = Float32Array(1);
  double toFloat32() => (_floatConverter..[0] = this)[0];
}