native icon indicating copy to clipboard operation
native copied to clipboard

Structs are missing setters for dart-style enum members

Open Levi-Lesches opened this issue 3 weeks ago • 0 comments

From this C API:

typedef enum MyEnum {
  a,
  b,
  c
} MyEnum;

typedef struct MyStruct {
  int x;
  float y;
  MyEnum z;
} MyStruct;

ffigen generates this Dart API:

// 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;

enum MyEnum {
  a(0),
  b(1),
  c(2);

  final int value;
  const MyEnum(this.value);

  static MyEnum fromValue(int value) => switch (value) {
    0 => a,
    1 => b,
    2 => c,
    _ => throw ArgumentError('Unknown value for MyEnum: $value'),
  };
}

final class MyStruct extends ffi.Struct {
  @ffi.Int()
  external int x;

  @ffi.Float()
  external double y;

  @ffi.UnsignedInt()
  external int zAsInt;

  MyEnum get z => MyEnum.fromValue(zAsInt);
}

MyStruct.z is generated as external int zAsInt with a getter MyEnum get z, but there is no set z(MyEnum):

  set z(MyEnum value) => zAsInt = value.value;

This allows the following code to compile and run

void main() {
  final struct = malloc<MyStruct>();
  struct.ref.zAsInt = 0;
  print(struct.ref.z == MyEnum.a);
  struct.ref.z = MyEnum.b;
  print(struct.ref.z == MyEnum.b);
}

I may be missing a reason why we didn't cover this before, but it looks like it should be simple enough?

Levi-Lesches avatar Nov 12 '25 20:11 Levi-Lesches