Search code examples
flutterdartdart-ffi

How to map Dart String with FFI


I've the Dart type as:

typedef dart_func = String Function(String x);

And want to map it with Dart FFi, but their could not find neither String, nor Utf8, I tried

typedef ffi_func = ffi.Pointer<Utf8> Function(ffi.Pointer<Utf8> x);

But it failed, and gave that Utf8 isn't a type


Solution

  • You need to include the ffi package too: https://pub.dev/packages/ffi

    Simple usage is:

    import 'package:ffi/ffi.dart';
    
      final foo = 'foo';
      final fooNative = foo.toNativeUtf8(); // a Pointer<Utf8>
    
      // given a Pointer<Utf8>, get a Dart string
      final fooDart = fooNative.toDartString();
    
      // don't forget to free the pointer created by toNativeUtf8
      malloc.free(fooNative); 
    

    Example code is here: https://github.com/dart-lang/samples/blob/master/ffi/structs/structs.dart