下面给出一个完整示例,演示如何在 Flutter 平台通过 Dart FFI 调用本地 mmap() 函数,实现零拷贝读取大文件。示例包含:
- C 代码(mmap_helper.c + mmap_helper.h)
- Android 端 CMake + Gradle 配置
- iOS 端 Xcode 集成说明
- Dart 端 FFI 绑定与封装
1. C 源码
mmap_helper.h
#ifndef MMAP_HELPER_H
#define MMAP_HELPER_H
#include <stddef.h>
#ifdef __cplusplus
extern "C" {
#endif
// 返回映射地址,失败返回 NULL
void* mmap_file(const char* path, size_t* length);
// 解除映射
int munmap_file(void* addr, size_t length);
#ifdef __cplusplus
}
#endif
#endif // MMAP_HELPER_H
mmap_helper.c
#include "mmap_helper.h"
#include <sys/mman.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
void* mmap_file(const char* path, size_t* length) {
if (!path || !length) return NULL;
int fd = open(path, O_RDONLY);
if (fd < 0) {
perror("open");
return NULL;
}
struct stat st;
if (fstat(fd, &st) < 0) {
perror("fstat");
close(fd);
return NULL;
}
*length = (size_t)st.st_size;
if (*length == 0) {
close(fd);
return NULL;
}
void* addr = mmap(NULL, *length, PROT_READ, MAP_PRIVATE, fd, 0);
close(fd);
if (addr == MAP_FAILED) {
perror("mmap");
return NULL;
}
return addr;
}
int munmap_file(void* addr, size_t length) {
if (!addr || length == 0) return -1;
return munmap(addr, length);
}
2. Android 端配置
假设你的 Flutter 项目结构是标准的,native 代码放在 android/app/src/main/cpp/。
目录结构示例:
android/app/src/main/cpp/
├── mmap_helper.c
├── mmap_helper.h
└── CMakeLists.txt
CMakeLists.txt
cmake_minimum_required(VERSION 3.10.2)
project(mmap_helper)
add_library(mmap_helper SHARED
mmap_helper.c
)
find_library(log-lib log)
target_link_libraries(mmap_helper
${log-lib}
)
android/app/build.gradle
android {
...
defaultConfig {
...
externalNativeBuild {
cmake {
cppFlags ""
}
}
}
externalNativeBuild {
cmake {
path "src/main/cpp/CMakeLists.txt"
}
}
}
3. iOS 端集成
iOS 端不需要额外编译 C 代码为动态库,可以直接将 C 文件添加到 Xcode 工程中。
- 打开
ios/Runner.xcworkspace。
- 在
Runner target 下,右键点击 Runner 文件夹,选择 Add Files to "Runner"。
- 选择
mmap_helper.c 和 mmap_helper.h,确保添加到 Runner target。
- Xcode 会自动编译 C 代码。
4. Dart 端 FFI 绑定与封装
lib/mmap_helper.dart
import 'dart:ffi';
import 'dart:io';
import 'package:ffi/ffi.dart';
typedef mmap_file_native = Pointer<Void> Function(Pointer<Utf8> path, Pointer<Size> length);
typedef MmapFile = Pointer<Void> Function(Pointer<Utf8> path, Pointer<Size> length);
typedef munmap_file_native = Int32 Function(Pointer<Void> addr, Size length);
typedef MunmapFile = int Function(Pointer<Void> addr, int length);
class MmapHelper {
late final DynamicLibrary _lib;
late final MmapFile _mmapFile;
late final MunmapFile _munmapFile;
MmapHelper() {
if (Platform.isAndroid) {
_lib = DynamicLibrary.open("libmmap_helper.so");
} else if (Platform.isIOS) {
_lib = DynamicLibrary.process();
} else {
throw UnsupportedError("Unsupported platform");
}
_mmapFile = _lib.lookupFunction<mmap_file_native, MmapFile>("mmap_file");
_munmapFile = _lib.lookupFunction<munmap_file_native, MunmapFile>("munmap_file");
}
/// 返回映射的内存地址和长度
/// 失败返回 null
MmapResult? mmapFile(String path) {
final pathPtr = path.toNativeUtf8();
final lengthPtr = calloc<Size>();
final addr = _mmapFile(pathPtr, lengthPtr);
calloc.free(pathPtr);
if (addr == nullptr) {
calloc.free(lengthPtr);
return null;
}
final length = lengthPtr.value;
calloc.free(lengthPtr);
return MmapResult(addr, length);
}
/// 解除映射
int munmapFile(MmapResult result) {
return _munmapFile(result.addr, result.length);
}
}
class MmapResult {
final Pointer<Void> addr;
final int length;
MmapResult(this.addr, this.length);
/// 读取映射内存为 Dart Uint8List(零拷贝不可能,需拷贝)
/// 如果想零拷贝访问,可以用 Pointer<Uint8> 直接访问
Pointer<Uint8> get pointer => addr.cast<Uint8>();
}
5. Flutter 端示例使用
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'mmap_helper.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: const Text('mmap FFI Demo')),
body: const MmapDemo(),
),
);
}
}
class MmapDemo extends StatefulWidget {
const MmapDemo({super.key});
@override
State<MmapDemo> createState() => _MmapDemoState();
}
class _MmapDemoState extends State<MmapDemo> {
final _mmapHelper = MmapHelper();
String? _fileContent;
@override
void initState() {
super.initState();
_readFile();
}
Future<void> _readFile() async {
// 请替换为设备上存在的文件路径
const filePath = "/sdcard/Download/large_file.txt";
final result = _mmapHelper.mmapFile(filePath);
if (result == null) {
setState(() {
_fileContent = "Failed to mmap file";
});
return;
}
// 这里演示读取前100字节内容
final ptr = result.pointer;
final length = result.length;
final readLength = length < 100 ? length : 100;
final bytes = ptr.asTypedList(readLength);
final content = String.fromCharCodes(bytes);
_mmapHelper.munmapFile(result);
setState(() {
_fileContent = content;
});
}
@override
Widget build(BuildContext context) {
return Center(
child: Text(_fileContent ?? "Loading..."),
);
}
}
总结
- C 代码实现 mmap 和 munmap。
- Android 通过 CMake 编译成动态库。
- iOS 直接集成 C 文件。
- Dart 通过 FFI 调用 mmap,返回内存指针和长度。
- Flutter 端示例演示如何读取文件内容。
如果需要,我可以帮你生成完整的 Flutter 项目模板,或者帮你调试具体问题。