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?

0

1 Answer 1

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.