native
native copied to clipboard
Offer native struct constructors
When working with C structs, I find I have to have a few lines dedicated to allocating a struct pointer and initializing the fields.
// C API
typedef struct MyStruct {
int x;
float y;
MyEnum z;
} MyStruct;
// ignore_for_file: unused_element
// AUTO GENERATED FILE, DO NOT EDIT.
//
// Generated by `package:ffigen`.
// ignore_for_file: type=lint, unused_import
import 'dart:ffi' as ffi;
final class MyStruct extends ffi.Struct {
@ffi.Int()
external int x;
@ffi.Float()
external double y;
}
// Application code
final structPtr = arena<MyStruct>()
..ref.x = 1;
..ref.y = 2.3;
What if ffigen could generate a constructor instead?
// Generated as part of MyStruct
static Pointer<MyStruct> allocate(
Allocator allocator, {
required int x,
required double y,
}) => allocator<MyStruct>()
..ref.x = x
..ref.y = y;
And then we can instead do
final structPtr = MyStruct.allocate(x: 1, y: 2.3, allocator: arena);
This would be helpful for structs with lots of fields.