ffi
Note there are two ffi packages:
One is builtin:
dart:ffi
One is
package:ffi/ffi.dart
https://pub.dev/documentation/ffi/latest/ffi/ffi-library.html
Doc for dart:io
:
Doc for dart:ffi
: https://api.dart.dev/stable/3.4.0/dart-ffi/dart-ffi-library.html
Examples for ffi
: https://github.com/dart-lang/samples/tree/main/ffi
types
char -> Char
double -> Double
float -> Float
int -> Int
int8 -> Int8
int16 -> Int16
int32 -> Int32
int64 -> Int64
intptr_t -> IntPtr
long -> Long
// void xxx();
typedef HelloWorldFunc = ffi.Void Function();
# create a pluggin
flutter create --template=plugin --platforms=android,ios mybatteryplugin
./code/ffi/a.h
1extern "C" int add(int a, int b);
./code/ffi/a.cc
1#include "a.h"
2int add(int a, int b) { return a + b; }
./code/ffi/hello.dart
1import 'dart:ffi' as ffi;
2import 'dart:io' show Platform, Directory;
3import 'package:path/path.dart' as path;
4
5typedef HelloWorldFunc = ffi.Int Function(ffi.Int, ffi.Int);
6
7typedef HelloWorld = int Function(int, int);
8
9void main() {
10 var libraryPath = path.join(Directory.current.path, 'libfoo.so');
11 if (Platform.isMacOS) {
12 libraryPath = path.join(Directory.current.path, 'libfoo.dylib');
13 }
14 final dylib = ffi.DynamicLibrary.open(libraryPath);
15
16 // Look up the C function 'hello_world'
17 final HelloWorld hello =
18 dylib.lookup<ffi.NativeFunction<HelloWorldFunc>>('add').asFunction();
19 print(hello(2, 3));
20}
./code/ffi/pubspec.yaml
1name: hello_ffi
2
3environment:
4 sdk: ^3.4.0
5
6dependencies:
7 path: ^1.8.0
./code/ffi/run.sh
1#!/usr/bin/env bash
2
3g++ -c -fPIC -o a.o a.cc
4g++ -shared -o libfoo.dylib ./a.o
5ls -lh
6nm libfoo.dylib