I created a struct with 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;
}
}
I want to create a reference of TestStruct
and use it. So I wrote the code.
TestStruct test = TestStruct("Text", 10, true);
but this is an error
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'.
I tried searching with the api documentation, but I didn't understand. Do you know how to create a struct as a reference?? thank you.
CodePudding user response:
Example:
class InAddr extends Struct {
factory InAddr.allocate(int sAddr) =>
calloc<InAddr>().ref
..sAddr = sAddr;
@Uint32()
external int sAddr;
}
You can allocate this with calloc function
final Pointer<InAddr> inAddress = calloc<InAddr>();
And free the pointer with
calloc.free(inAddress);