Question #114EasyDart Basics

What is Dart: ffi (Foreign Function Interface)

#dart

Answer

Overview

Dart FFI (Foreign Function Interface) allows Dart code to directly call functions written in C (or other languages compiled to native shared libraries). It bridges Dart and native code without a platform channel.


When to Use Dart FFI

Use CaseExample
Performance-critical codeImage processing, encryption
Existing C/C++ librariesOpenCV, SQLite, libssl
Platform APIs not in FlutterDirect OS calls
No method channel overheadReal-time audio, DSP

Basic FFI Example

dart
// lib/native_math.dart
import 'dart:ffi';
import 'dart:io';

// Load the shared library
final DynamicLibrary nativeLib = Platform.isAndroid
    ? DynamicLibrary.open('libnative.so')
    : DynamicLibrary.process(); // iOS links statically

// C function signature: int add(int a, int b);
typedef AddC = Int32 Function(Int32 a, Int32 b);
typedef AddDart = int Function(int a, int b);

// Look up the function
final add = nativeLib.lookupFunction<AddC, AddDart>('add');

void main() {
  print(add(3, 4)); // Calls native C: 7
}

C Code Side (native_math.c)

c
// native_math.c
#include <stdint.h>

int32_t add(int32_t a, int32_t b) {
    return a + b;
}

// More complex example
double calculate_average(double* arr, int32_t length) {
    double sum = 0;
    for (int i = 0; i < length; i++) sum += arr[i];
    return sum / length;
}

FFI Types Mapping

Dart FFI TypeC TypeDart Type
text
Int8
text
int8_t
text
int
text
Int32
text
int32_t
text
int
text
Int64
text
int64_t
text
int
text
Float
text
float
text
double
text
Double
text
double
text
double
text
Bool
text
bool
text
bool
text
Pointer<T>
text
T*
text
Pointer<T>
text
Void
text
void
text
void

With Strings and Structs

dart
import 'dart:ffi';
import 'package:ffi/ffi.dart'; // For Utf8 support

// Calling C function that takes/returns strings
typedef GetMessageC = Pointer<Utf8> Function();
final getMessage = nativeLib
    .lookupFunction<GetMessageC, Pointer<Utf8> Function()>('get_message');

final messagePtr = getMessage();
print(messagePtr.toDartString()); // Convert C string to Dart String

FFI vs Platform Channels

FeatureFFIPlatform Channels
LanguageC/C++Native (Swift/Kotlin)
Overhead✅ Very low❌ Message passing
ComplexityHighMedium
Use casePerformance-critical math/cryptoPlatform UI, sensors

Note: FFI is powerful but complex. For most Flutter plugins, Method Channels are simpler. Use FFI when you need direct C library access with minimal overhead.