Skip to content

Structs are missing setters for dart-style enum members #2784

@Levi-Lesches

Description

@Levi-Lesches

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?

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions