在 Dart 中将 int 转换为 Uint8

tem*_*mp_ 3 dart flutter dart-ffi

我正在使用ffityed_dataDart 库,并不断遇到这行代码的错误,

 Uint8 START_OF_HEADER = 1 as Uint8;
Run Code Online (Sandbox Code Playgroud)

我的错误:

类型“int”不是类型转换中“Uint8”类型的子类型

我在这里做错了什么?另一个奇怪的事情是,我可以使用这些库编写这行代码,并且我的 IDE 将编译并且不会抛出错误,直到您使用该行代码。我正在使用 Intellij 版本 2019.2.4

Ric*_*eap 5

您正在尝试Uint8在 Dart 中创建 a 的实例,但这是不可能的 - 该类型只是一个标记。

/// [Uint8] is not constructible in the Dart code and serves purely as marker in
/// type signatures.
Run Code Online (Sandbox Code Playgroud)

您只需在 typedef 中使用这些标记,例如来描述一个 C 函数,它采用两个有符号的 32 位整数并返回有符号的 32 位整数:

typedef native_sum_func = Int32 Function(Int32 a, Int32 b);
Run Code Online (Sandbox Code Playgroud)

这将与等效的类似 Dart 的 typedef 配对

typedef NativeSum = int Function(int a, int b);
Run Code Online (Sandbox Code Playgroud)

镖FFI负责转换ab从镖整数成32个C整数,以及用于将返回值返回到一个镖INT。

请注意,您可以创建指向这些 C 类型的指针,例如Pointer<Uint8>使用allocate方法 from package:ffi