flutter 如何创建一个 dart:ffi 结构引用

flutter how to create an dart:ffi struct reference

我用 dart:ffi 创建了一个结构。

import 'dart:ffi';
import 'package:ffi/ffi.dart';

class TestStruct extends Struct{
   external Pointer<Utf8> strText;
   
   @Int32()
   external int nNum;

   @Bool()
   external bool bIsTrue;


   //contstruct
   TestStruct(String str, int number, bool state){
      strText = str as Pointer<Utf8>;
      nNum = number as int;
      bIsTrue = state as bool;
   }
}

我想创建 TestStruct 的引用并使用它。所以我写了代码。

TestStruct test = TestStruct("Text", 10, true);

但这是一个错误

Subclasses of 'Struct' and 'Union' are backed by native memory, and can't be instantiated by a generative constructor.  
Try allocating it via allocation, or load from a 'Pointer'.

我尝试使用 api 文档进行搜索,但我不明白。你知道如何创建一个结构作为参考吗?谢谢。

示例:

class InAddr extends Struct {

  factory InAddr.allocate(int sAddr) =>
      calloc<InAddr>().ref
        ..sAddr = sAddr;
        
  @Uint32()
  external int sAddr;
}

您可以使用 calloc 函数分配它

final Pointer<InAddr> inAddress = calloc<InAddr>();

并用

释放指针
calloc.free(inAddress);

根据文档,您无法创建 Struct 类 的实例: https://api.flutter.dev/flutter/dart-ffi/Struct-class.html

但是,您通常需要指点。所以你可以想出类似的东西:

static Pointer<InAddr> allocate(int sAddr) {
    final pointer = calloc<InAddr>();
    pointer.ref.sAddr = sAddr;
    return pointer;
}