How to map Dart String with FFI
Asked Answered
T

1

9

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

Tidal answered 17/2, 2020 at 20:54 Comment(0)
C
14

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

Conclude answered 18/2, 2020 at 2:40 Comment(2)
Importing ffi package does not really solve the issue for me. Any potential wrong doings?Flavoprotein
Be sure to import 'package:ffi/ffi.dart';Unsay

© 2022 - 2024 — McMap. All rights reserved.