Struct
- Dart course
- Expert
- Lesson 16/47
- 5 min
Learn C structs with Struct.
Struct
Struct is the dart:ffi class that represents C structs on the Dart side. A Struct is declared with extends Struct and declares the C-side fields with annotations like @Int32() on the Dart side.
For example, class Point extends Struct { @Int32() external int x; @Int32() external int y; } is the equivalent of struct Point { int x; int y; } in C. Struct fields are external; this indicates the memory is managed on the C side.
Struct memory layout
The order and type of struct fields must match the C struct's memory layout exactly. Otherwise data corruption occurs. @Int32() takes 4 bytes, @Double() 8 bytes, @Int8() 1 byte.
Structs are referenced via Pointer<Point> and accessed with Pointer.ref. Struct memory is either allocated on the C side or from Dart with calloc/malloc. If memory is not freed, a leak occurs.
Practice A StructInfo class
Define a StructInfo class with final String name; final int fieldCount; StructInfo(this.name, this.fieldCount); field and constructor. Add a String describe() => '$name: $fieldCount fields'; method. In main create final si = StructInfo('Point', 2);; print with print(si.describe());.
Starter code
void main() {
// define a StructInfo class (name, fieldCount; describe)
// create a StructInfo; print describe()
}Sample solution
class StructInfo {
final String name;
final int fieldCount;
StructInfo(this.name, this.fieldCount);
String describe() => '$name: $fieldCount fields';
}
void main() {
final si = StructInfo('Point', 2);
print(si.describe());
}Expected output
Point: 2 fields
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 How is a Struct declared?
- With extends Struct Correct answer
- With extends Class
- With implements Struct
- With with Struct
Explanation: a Struct is declared with extends Struct.
2 Match the Struct parts
| Term | Meaning |
|---|---|
extends Struct |
Declaration form |
@Int32() |
Field annotation |
external |
Memory on C side |
Pointer<T> |
Struct reference |
3 A Struct annotation
class Point extends Struct {
@____() external int x;
}
class Point extends Struct {
@Int32() external int x;
}
Explanation: @Int32() declares an int field as 4 bytes.