【问题标题】:Casting an int to Uint8 in Dart在 Dart 中将 int 转换为 Uint8
【发布时间】:2020-03-03 07:19:01
【问题描述】:

我正在使用ffityed_data Dart 库,这行代码一直出错,

 Uint8 START_OF_HEADER = 1 as Uint8;

我的错误:

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

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

【问题讨论】:

    标签: flutter dart dart-ffi


    【解决方案1】:

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

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

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

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

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

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

    Dart ffi 负责将 ab 从 Dart int 转换为 32 位 C int,并将返回值转换回 Dart int。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-05
      • 2016-03-12
      相关资源
      最近更新 更多