Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is 'Native Type' for 'char*' in dart FFI?

Tags:

dart

ffi

dart-ffi

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?

like image 332
Hamed Avatar asked Oct 15 '25 14:10

Hamed


1 Answers

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.

like image 148
lrn Avatar answered Oct 17 '25 02:10

lrn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!