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

Jun*_*won 5 struct ffi dart flutter

我创建了一个结构体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;
   }
}
Run Code Online (Sandbox Code Playgroud)

我想创建一个参考TestStruct并使用它。所以我写了代码。

TestStruct test = TestStruct("Text", 10, true);
Run Code Online (Sandbox Code Playgroud)

但这是一个错误

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'.
Run Code Online (Sandbox Code Playgroud)

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

小智 5

例子:

class InAddr extends Struct {

  factory InAddr.allocate(int sAddr) =>
      calloc<InAddr>().ref
        ..sAddr = sAddr;
        
  @Uint32()
  external int sAddr;
}
Run Code Online (Sandbox Code Playgroud)

您可以使用 calloc 函数分配它

final Pointer<InAddr> inAddress = calloc<InAddr>();
Run Code Online (Sandbox Code Playgroud)

并释放指针

calloc.free(inAddress);
Run Code Online (Sandbox Code Playgroud)