3

I have a function like this in C language:

char* getString() {
    return "SOME_STRING";
}

now I want to invoke it by FFI in dart, and this is my code:

import 'dart:io';
import 'dart:ffi';

void main(List<String> arguments) {
  print('${getString()}');
}

final DynamicLibrary nativeAppTokenLib = Platform.isAndroid
    ? DynamicLibrary.open('lib_native_get_string.so')
    : DynamicLibrary.process();

final String Function() getString = nativeAppTokenLib
    .lookup<NativeFunction<*** Function()>>('getString')
    .asFunction();

I wonder what should I put instead of *** as the native type?

Hamed
  • 5,867
  • 4
  • 32
  • 56

1 Answers1

6

Try:

import 'dart:ffi';
import 'dart:io';
import "package:ffi/ffi.dart";

...

final Pointer<Utf8> Function() _getString = nativeAppTokenLib
    .lookup<NativeFunction<Pointer<Utf8> Function()>>('getString')
    .asFunction();
String getString() => _getString().toDartString();

This uses package:ffi's Utf8 type to represent characters. The toDartString extension method on Pointer<Utf8> is the intended way to convert those to a string.

lrn
  • 64,680
  • 7
  • 105
  • 121