Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Getting data array as iterable from C/C++ using ffi? #902

Closed
kakyoism opened this issue Mar 30, 2020 · 1 comment
Closed

Getting data array as iterable from C/C++ using ffi? #902

kakyoism opened this issue Mar 30, 2020 · 1 comment
Labels
request Requests to resolve a particular developer problem

Comments

@kakyoism
Copy link

kakyoism commented Mar 30, 2020

The official flutter tutorial on C/C++ interop through ffi only touches on calling a C++ function and getting a single return value.

Goal

What if I have a data buffer created on C/C++ side, but want to deliver to dart/flutter-side to show using the natural iteration syntax?

Problem

I'm testing Dart's FFI by trying to have safe memory deallocation from Dart to C/C++. The test reuses the official struct sample .

I could get the Array as a dart Pointer, but it's unclear to me how to iterate the array as a collection easily.

Code

I'm implementing a Dart-side C array binding like this:

In struct.h

struct Array
{
	int* array;
	int len;
};

and a pair of simple allocation/deallocation test functions:

struct Array* get_array();
int del_array(struct Array* arr);

Then on Dart side in structs.dart:

typedef get_array_func = Pointer<Array> Function();
typedef del_array_func = void Function(int arrAddress);

...

  final getArrayPointer = dylib.lookup<NativeFunction<get_array_func>>('get_array');
  final getArray = getArrayPointer.asFunction<get_array_func>();
  final arrayPointer = getArray();
  final array = arrayPointer.ref.array;
  print('array.array: $array');

This gives me the print out

array.array: Pointer<Int32>: address=0x7fb0a5900000

Question

Can I convert the array pointer to a List easily? Something like:

final array = arrayPointer.ref.array.toList();
array.forEach(idx, elem) => print("array[$idx]: $elem");
@kakyoism kakyoism added the request Requests to resolve a particular developer problem label Mar 30, 2020
@kakyoism
Copy link
Author

kakyoism commented Mar 30, 2020

So asTypedList() is the answer

  final arrReal = array.asTypedList(10);
  arrReal.forEach((idx, elem) => print("array[$idx]: $elem"));

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
request Requests to resolve a particular developer problem
Projects
None yet
Development

No branches or pull requests

1 participant