跳过主内容

native_field_invalid_type

'{0}' 是原生字段不支持的类型。原生字段仅支持指针、数组或数字和复合类型。

描述

#

当带有 @Native 注解的字段具有原生字段不支持的类型时,分析器会生成此诊断信息。

原生字段支持指针、数组、数字类型以及 Compound 的子类型(即结构体或联合体)。NativeType 的其他子类型,例如 HandleNativeFunction,不允许作为原生字段。

原生函数应与外部函数一起使用,而不是外部字段。

不支持 Handle,因为无法透明地将 Dart 对象加载和存储到指针中。

有关 FFI 的更多信息,请参阅 使用 dart:ffi 进行 C 互操作

示例

#

以下代码会生成此诊断信息,因为字段 free 使用了不支持的原生类型 NativeFunction

dart
import 'dart:ffi';

@Native<NativeFunction<Void Function()>>()
external void Function() free;

常见修复方法

#

如果您想使用 NativeFunction 字段绑定到现有的原生函数,请改用 @Native 方法

dart
import 'dart:ffi';

@Native<Void Function(Pointer<Void>)>()
external void free(Pointer<Void> ptr);

要在 C 中绑定到存储函数指针的字段,请为 Dart 字段使用指针类型

dart
import 'dart:ffi';

@Native()
external Pointer<NativeFunction<Void Function(Pointer<Void>)>> free;