Home > Software design >  Dart/Flutter FFI: Convert List to Array
Dart/Flutter FFI: Convert List to Array

Time:01-22

I have a struct that receives an array of type Float from C library.

class MyStruct extends Struct{      
  @Array.multi([12])
  external Array<Float> states;
}

I am able to recive data and parse it in Dart. Now I want to do the other way round. I have list of double which I want to assign to this struct and pass to C .

The following cast fails at run time.

myStructObject.states = listObject as Array<Float>;

Neither Array class, nor List class has any related methods. Any idea on this?

CodePudding user response:

There's no way to get around copying elements into FFI arrays.

for (var i = 0; i < listObject.length; i  ) {
  my_struct.states[i] = listObject[i];
}

This may seem inefficient, but consider that depending on the specialization of listObject, the underlying memory layout of the data may differ significantly from the contiguous FFI layout, and so a type conversion sugar provided by Dart would likely also need to perform conversions on individual elements anyways (as opposed to just performing a single memcpy under the hood).

One possibility for closing the convenience gap would be to define an extension method. For example:

extension FloatArrayFill<T> on ffi.Array<ffi.Float> {
  void fillFromList(List<T> list) {
    for (var i = 0; i < list.length; i  ) {
      this[i] = list[i] as double;
    }
  }
}

Usage:

my_struct.states.fillFromList(list);

Note that a separate extension method would be need to be defined for each ffi.Array<T> specialization you want to do this for (Array<Uint32>, Array<Double>, Array<Bool>, etc.). This is due to the [] operator being implemented through a separate extension method for each of these type specializations internally.

  •  Tags:  
  • Related