Search code examples
dartgenericsffidart-ffi

type safe memory allocation with dart ffi


I'm trying to make my code a little more robust when allocating memory for ffi.

I've written the following function:

void withMemory<T extends NativeType>(
    int size, void Function(Pointer<T> memory) action) {
  final memory = calloc<Int8>(size);
  try {
    action(memory.cast());
  } finally {
    calloc.free(memory);
  }
}

To call the above function I use:

withMemory<Uint32>(sizeOf<Uint32>(), (phToken) {
  // use the memory allocated to phToken
});

This works but as you can see I need to pass Uint32 twice as well as the sizeOf.

What I really want to write is:

withMemory<Uint32>((phToken) {
  // use the memory allocated to phToken
});

The problem is that you can't pass a generic type to either calloc or sizeOf without the error:

The type arguments to [...] must be compile time constants but type parameters are not constants. Try changing the type argument to be a constant type.

Is there any way around this problem?


Solution

  • This can now be done with the Arena allocator from package:ffi.

    using((Arena arena) {
      final p = arena<Uint32>();
      // Use the memory allocated to `p`.
    }
    // Memory freed.
    

    Documentation: