create<T extends Struct> 静态方法
- @Since('3.4')
在 typedData
中创建字节的 struct 视图。
创建的 struct 子类的实例将作为 TypedData.offsetInBytes 加 offset
倍的 TypedData.elementSizeInBytes 的字节支持。也就是说,子类声明的外部实例变量的获取器和设置器将从 TypedData.buffer 的 typedData
的字节中读取和写入它们的值,从 TypedData.offsetInBytes 加 offset
倍的 TypedData.elementSizeInBytes 开始。 typedData
的 TypedData.lengthInBytes 必须 足够容纳 struct 子类的 sizeOf。 例如,typedData
是一个 Uint8List、一个 Float64List 或任何其他 TypedData,它只被处理为通过其 TypedData.buffer、TypedData.offsetInBytes 和 TypedData.lengthInBytes 的 ByteBuffer 视图。
如果省略了 typedData
,则在 Dart 堆上分配一个全新的 ByteBuffer,其字节数正好足以容纳创建的 struct 的大小,并将其用作存储 struct 字段的内存。
如果提供了 offset
,则 typedData
的索引将偏移 offset
倍的 TypedData.elementSizeInBytes。
示例
final class Point extends Struct {
@Double()
external double x;
@Double()
external double y;
/// Creates Dart managed memory to hold a `Point` and returns the
/// `Point` view on it.
factory Point(double x, double y) {
return Struct.create()
..x = x
..y = y;
}
/// Creates a [Point] view on [typedData].
factory Point.fromTypedData(TypedData typedData) {
return Struct.create(typedData);
}
}
要从 Pointer 创建 struct 对象,请使用 StructPointer.ref。
实现
@Since('3.4')
external static T create<T extends Struct>([TypedData typedData, int offset]);