我正在使用 ffi
和 tyed_data
Dart 库并在这行代码中一直遇到错误,
Uint8 START_OF_HEADER = 1 as Uint8;
我的错误:
type 'int' is not a subtype of type 'Uint8' in type cast
我在这里做错了什么?另一件奇怪的事情是,我可以使用这些库编写这行代码,我的 IDE 将编译并且不会抛出错误,直到您使用该行代码。我使用的是 Intellij 版本 2019.2.4
最佳答案
您正在尝试创建 Uint8
的实例在 Dart 中,但这是不可能的 - 该类型只是一个标记。
/// [Uint8] is not constructible in the Dart code and serves purely as marker in
/// type signatures.
您只需在 typedef 中使用这些标记,例如描述一个 C 函数接受两个带符号的 32 位整数并返回带符号的 32 位整数:
typedef native_sum_func = Int32 Function(Int32 a, Int32 b);
这将与等效的类 Dart typedef 配对
typedef NativeSum = int Function(int a, int b);
Dart ffi 负责转换a
和 b
从 Dart 整数转换为 32 位 C 整数并将返回值转换回 Dart 整数。
请注意,您可以创建指向这些 C 类型的指针,例如 Pointer<Uint8>
使用 allocate
方法来自 package:ffi
.
关于flutter - 在 Dart 中将 int 转换为 Uint8,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58736379/