Casting an int to Uint8 in Dart

2,655

You are trying to create an instance of a Uint8 in Dart, but that's not possible - that type is just a marker.

/// [Uint8] is not constructible in the Dart code and serves purely as marker in
/// type signatures.

You'll just use those markers in the typedefs, for example to describe a C function taking two signed 32 bit ints and returning signed 32 bit int:

typedef native_sum_func = Int32 Function(Int32 a, Int32 b);

this will be paired with an equivalent Dart-like typedef

typedef NativeSum = int Function(int a, int b);

Dart ffi is responsible for converting a and b from Dart ints into 32 bit C ints and for converting the return value back to a Dart int.

Note that you can create a pointer to these C types, for example Pointer<Uint8> using the allocate method from package:ffi.

Share:
2,655
temp_
Author by

temp_

Updated on December 15, 2022

Comments

  • temp_
    temp_ over 1 year

    I am using the ffi and tyed_data Dart libraries and keep running into an error with this line of code,

     Uint8 START_OF_HEADER = 1 as Uint8;
    

    My error:

    type 'int' is not a subtype of type 'Uint8' in type cast

    What am I doing wrong here? Another strange thing is that I can write this line of code using these libraries and my IDE will compile and not throw an error, that is until you use that line of code. I'm using Intellij version 2019.2.4