Binding to C native code with dart:ffi: pass strings to C

1,882 views
Skip to first unread message

alopez

unread,
Apr 28, 2020, 2:12:02 AM4/28/20
to Flutter Development (flutter-dev)

Hi,
I am trying to do my first plugin using a native c library but I don't know how to pass a string to a native c function. I have seen this dart example that use Utf8 Class but It doesn't exist in flutter.

import 'package:ffi/ffi.dart';
import 'dart:io' show Platform;

// C string parameter pointer function - char *reverse(char *str, int length);
typedef reverse_func = Pointer<Utf8> Function(Pointer<Utf8> str, Int32 length);
typedef Reverse = Pointer<Utf8> Function(Pointer<Utf8> str, int length);



main
() {
 
var path = './structs_library/libstructs.so';
 
if (Platform.isMacOS) path = './structs_library/libstructs.dylib';
 
if (Platform.isWindows) path = r'structs_library\Debug\structs.dll';
 
final dylib = DynamicLibrary.open(path);

 
final reversePointer = dylib.lookup<NativeFunction<reverse_func>>('reverse');
 
final reverse = reversePointer.asFunction<Reverse>();
 
final reversedMessage = Utf8.fromUtf8(reverse(Utf8.toUtf8('backwards'), 9));
 
print('$reversedMessage');
}



Could you provide me with an example to pass a string to a native c function?

Thanks




Tim Sneath

unread,
Apr 28, 2020, 1:24:44 PM4/28/20
to Flutter Development (flutter-dev)
You also need import 'dart:ffi'; to use the Pointer class.

Utf8 is part of the ffi package, so you should be able to use it from Flutter.

alopez

unread,
Apr 29, 2020, 2:02:16 AM4/29/20
to Flutter Development (flutter-dev)
Thanks for your reply. At the end it works but I don't know if there is an "easy" way to do it.I added ffi: ^0.1.3 to pubspec.yaml and use the import 'package:ffi/src/utf8.dart'
Reply all
Reply to author
Forward
0 new messages