好的,这是一个完整的 Flutter 零拷贝读取大文件示例,通过 Dart FFI 调用本地 mmap() 函数。
项目结构:
your_flutter_app/
├── android/
│ ├── app/
│ │ ├── build.gradle # Android Gradle配置
│ │ └── src/main/cpp/
│ │ └── CMakeLists.txt # Android CMake配置
├── c/ # C 源代码目录
│ ├── mmap_helper.c
│ └── mmap_helper.h
├── ios/
│ ├── Runner/ # iOS Runner target目录
│ │ ├── mmap_helper.c # C源文件 (添加到Xcode项目)
│ │ └── mmap_helper.h # C头文件 (添加到Xcode项目)
│ └── Runner.xcodeproj/ # Xcode项目文件 (需要手动配置)
├── lib/
│ ├── main.dart # 主应用代码
│ └── mmap_util.dart # Dart FFI绑定和封装
└── pubspec.yaml # Flutter依赖
1. C 源码 (c/mmap_helper.c 和 c/mmap_helper.h)
这些文件包含了 mmap 和 munmap 的简单 C 包装函数,以及文件打开、关闭和获取大小的函数。
c/mmap_helper.h:
#ifndef MMAP_HELPER_H
#define MMAP_HELPER_H
#ifdef __cplusplus
extern "C" {
#endif
#include <stddef.h> // for size_t
#include <sys/types.h> // for off_t
// 打开文件,返回文件描述符
// 成功返回文件描述符 (>= 0),失败返回 -1
int open_file_helper(const char* path);
// 获取文件大小
// 成功返回文件大小 (>= 0),失败返回 -1
long long get_file_size_helper(int fd);
// 将文件区域映射到内存
// Parameters:
// fd: 文件描述符
// length: 要映射的区域大小
// offset: 文件中的起始偏移量
// 成功返回映射的内存地址 (非 NULL),失败返回 NULL
void* map_file_read_helper(int fd, size_t length, off_t offset);
// 解除内存映射
// Parameters:
// addr: 映射的内存地址
// length: 映射的区域大小
// 成功返回 0,失败返回 -1
int unmap_file_helper(void* addr, size_t length);
// 关闭文件描述符
// 成功返回 0,失败返回 -1
int close_file_helper(int fd);
#ifdef __cplusplus
}
#endif
#endif // MMAP_HELPER_H
c/mmap_helper.c:
#include "mmap_helper.h"
#include <stdio.h> // for perror
#include <fcntl.h> // for open
#include <unistd.h> // for close, fstat
#include <sys/mman.h> // for mmap, munmap
#include <sys/stat.h> // for fstat
#include <errno.h> // for errno
// 打开文件
int open_file_helper(const char* path) {
int fd = open(path, O_RDONLY); // Open read-only
if (fd < 0) {
perror("open_file_helper: Error opening file");
}
return fd;
}
// 获取文件大小
long long get_file_size_helper(int fd) {
struct stat st;
if (fstat(fd, &st) < 0) {
perror("get_file_size_helper: Error getting file size");
return -1; // Indicate error
}
return st.st_size;
}
// 将文件区域映射到内存 (只读,私有映射)
void* map_file_read_helper(int fd, size_t length, off_t offset) {
// Use MAP_PRIVATE for read-only access if you don't need to write back
// Use MAP_SHARED if changes *could* be written back (though PROT_READ prevents it here)
// MAP_PRIVATE ensures changes to the memory view are not written to the file.
void* addr = mmap(NULL, length, PROT_READ, MAP_PRIVATE, fd, offset);
if (addr == MAP_FAILED) {
perror("map_file_read_helper: Error mapping file");
return NULL; // Indicate error
}
return addr;
}
// 解除内存映射
int unmap_file_helper(void* addr, size_t length) {
int result = munmap(addr, length);
if (result < 0) {
perror("unmap_file_helper: Error unmapping file");
}
return result;
}
// 关闭文件描述符
int close_file_helper(int fd) {
int result = close(fd);
if (result < 0) {
perror("close_file_helper: Error closing file");
}
return result;
}
2. Android 端配置 (CMake + Gradle)
android/src/main/cpp/CMakeLists.txt:
创建此文件,内容如下:
cmake_minimum_required(VERSION 3.18)
project("mmap_helper" VERSION "1.0.0")
# 添加 C 源码目录
# 你可以将 c/ 目录复制到 android/src/main/cpp/mmap_helper/
# 或者使用相对路径
# 假设你将 c/ 目录放在了 android/src/main/cpp/ 下面,即 android/src/main/cpp/c/
# 实际操作中,更推荐将 c/ 目录保持在项目根目录,然后在这里用相对路径引用
# 比如,如果 c/ 在项目根目录,这里可以写 ../../../../c/mmap_helper.c
# 为了示例简单,我们假设你把 c/ 目录整个复制到了 android/src/main/cpp/c/
# 或者直接把 mmap_helper.c 和 mmap_helper.h 复制到 android/src/main/cpp/
# 我们这里假设 mmap_helper.c 就在当前 cpp 目录下
add_library( # Sets the name of the library.
mmap_helper
# Sets the library type.
SHARED
# Provides a relative path to your source file(s).
mmap_helper.c)
# 寻找 Android 的 Log 库 (可选,如果 C 代码需要日志)
find_library( # Sets the name of the path variable.
log-lib
# Specifies the name of the NDK library that
# CMake should locate.
log )
# 将本地库与 log-lib 链接。
target_link_libraries( # Specifies the target library.
mmap_helper
# Links the log library to the target library.
${log-lib} )
android/app/build.gradle:
修改 android 块,添加 externalNativeBuild 配置:
android {
// ... other configurations
defaultConfig {
// ...
minSdkVersion 21 // FFI requires API 21+
// ...
}
// ... other configurations
externalNativeBuild {
cmake {
// 设置 CMakeLists.txt 的路径。
// 根据你放置 CMakeLists.txt 和 C 源文件的位置调整路径。
// 如果 CMakeLists.txt 在 android/src/main/cpp/,就像上面的例子,路径就是这个。
path "src/main/cpp/CMakeLists.txt"
version "3.18.1" // 使用一个合适的 CMake 版本
}
}
sourceSets {
main {
// 如果你的 C 源码不在默认的 android/src/main/cpp 目录下
// 例如,如果 C 源码在项目根目录的 c/ 目录下
// 你需要在 CMakeLists.txt 中正确引用它们,并且不需要修改 sourceSets。
// 如果你选择将 C 源码直接放在 android/src/main/cpp/mmap_helper 这样命名的子目录里,
// 并且 CMakeLists.txt 也放在这个子目录里,那么 externalNativeBuild.cmake.path 也要指向这个子目录。
// 为了简单,我们假设 C 源码 mmap_helper.c 和 CMakeLists.txt 都在 android/src/main/cpp/
// 在这种情况下,默认配置通常是够的,不需要额外修改 sourceSets.
}
}
}
重要: 将 c/mmap_helper.c 和 c/mmap_helper.h 文件复制到 android/src/main/cpp/ 目录下,以便 CMakeLists.txt 能够找到它们。
3. iOS 端配置 (Xcode 工程集成)
iOS 不需要 CMake 或额外的 Gradle 配置。Flutter CLI 会管理 Xcode 项目。你只需要将 C 源码文件添加到 Xcode 项目的 Runner target 中。
- 在 Xcode 中打开 Flutter 项目的 iOS 部分(打开
ios/Runner.xcworkspace)。
- 在项目导航器中,右键点击
Runner 组(通常位于顶部)。
- 选择 "Add Files to 'Runner'..."。
- 导航到你的
c/ 目录,选择 mmap_helper.c 和 mmap_helper.h。
- 在弹出的选项框中:
- 确保 "Copy items if needed" 被选中 (或者你可以手动管理文件位置,但复制通常更简单)。
- 确保 "Add to targets" 部分的
Runner 被选中。
- 点击 "Add"。
现在,这两个 C 文件应该出现在 Runner 组下,并且被添加到 Runner target 的 Compile Sources 和 Headers build phase 中。它们将作为主应用二进制的一部分被编译。
4. Dart 端 (FFI 绑定与封装)
pubspec.yaml:
添加 ffi 和 path_provider 依赖(path_provider 用于获取文件路径)。
dependencies:
flutter:
sdk: flutter
ffi: ^2.0.2 # 或者最新版本
path_provider: ^2.0.11 # 或者最新版本
dev_dependencies:
flutter_test:
sdk: flutter
flutter_lints: ^2.0.0
flutter:
uses-material-design: true
运行 flutter pub get 获取依赖。
lib/mmap_util.dart:
创建 FFI 绑定和 MmapFile 封装类。
import 'dart:ffi';
import 'dart:io';
import 'dart:typed_data';
import 'package:ffi/ffi.dart'; // for Utf8
// 定义 C 函数签名对应的 Dart 类型
typedef OpenFileC = Int32 Function(Pointer<Utf8> path);
typedef GetFileSizeC = Int64 Function(Int32 fd);
typedef MapFileReadC = Pointer<Void> Function(Int32 fd, IntPtr length, IntPtr offset);
typedef UnmapFileC = Int32 Function(Pointer<Void> addr, IntPtr length);
typedef CloseFileC = Int32 Function(Int32 fd);
// 定义 Dart 函数签名
typedef OpenFileDart = int Function(Pointer<Utf8> path);
typedef GetFileSizeDart = int Function(int fd);
typedef MapFileReadDart = Pointer<Void> Function(int fd, int length, int offset);
typedef UnmapFileDart = int Function(Pointer<Void> addr, int length);
typedef CloseFileDart = int Function(int fd);
// 加载本地库
final DynamicLibrary nativeLib = Platform.isAndroid
? DynamicLibrary.open("libmmap_helper.so") // Android
: DynamicLibrary.executable(); // iOS (C code compiled into the main executable)
// 查找并绑定 C 函数
final OpenFileDart _openFile =
nativeLib.lookupFunction<OpenFileC, OpenFileDart>('open_file_helper');
final GetFileSizeDart _getFileSize =
nativeLib.lookupFunction<GetFileSizeC, GetFileSizeDart>('get_file_size_helper');
final MapFileReadDart _mapFileRead =
nativeLib.lookupFunction<MapFileReadC, MapFileReadDart>('map_file_read_helper');
final UnmapFileDart _unmapFile =
nativeLib.lookupFunction<UnmapFileC, UnmapFileDart>('unmap_file_helper');
final CloseFileDart _closeFile =
nativeLib.lookupFunction<CloseFileC, CloseFileDart>('close_file_helper');
/// 一个封装了 mmap 文件操作的类。
class MmapFile {
final String path;
int _fd = -1;
Pointer<Void> _mappedAddress = nullptr;
int _fileSize = -1;
bool _isMapped = false;
MmapFile(this.path);
/// 打开文件并获取大小
Future<void> open() async {
if (_fd != -1) {
// Already opened
return;
}
final pathPtr = path.toNativeUtf8();
try {
_fd = _openFile(pathPtr);
if (_fd < 0) {
throw Exception('Failed to open file: $path');
}
_fileSize = _getFileSize(_fd);
if (_fileSize < 0) {
// Attempt to close the file descriptor on error
_closeFile(_fd);
_fd = -1; // Reset fd
throw Exception('Failed to get file size for $path');
}
} finally {
calloc.free(pathPtr);
}
}
/// 获取文件大小 (requires calling open() first)
int get fileSize {
if (_fileSize < 0) {
throw StateError('File must be opened first to get size.');
}
return _fileSize;
}
/// 将整个文件映射到内存
Uint8List map() {
if (_fd == -1) {
throw StateError('File must be opened first before mapping.');
}
if (_isMapped) {
throw StateError('File is already mapped.');
}
if (_fileSize == 0) {
// Cannot map an empty file
print('Warning: File is empty, cannot map.');
return Uint8List(0); // Return empty list for zero-size file
}
// Map the entire file from offset 0
_mappedAddress = _mapFileRead(_fd, _fileSize, 0);
if (_mappedAddress == nullptr) {
// Attempt to close the file descriptor on error? Or leave it open for potential re-attempts?
// Let's just throw, the user should dispose if mapping fails.
throw Exception('Failed to map file: $path');
}
_isMapped = true;
// Create a zero-copy view of the mapped memory
// Note: This view is only valid as long as the memory is mapped.
// You MUST call unmap() before the MmapFile object is discarded or the app exits,
// otherwise you will have memory leaks and potential crashes.
return _mappedAddress.cast<Uint8>().asTypedList(_fileSize);
}
/// 解除内存映射
void unmap() {
if (!_isMapped) {
print('Warning: File is not currently mapped.');
return;
}
if (_mappedAddress != nullptr) {
final result = _unmapFile(_mappedAddress, _fileSize);
if (result < 0) {
print('Error unmapping file: $path');
// Depending on criticality, you might throw an exception here.
// For now, we'll just print.
}
_mappedAddress = nullptr;
_isMapped = false;
}
}
/// 关闭文件描述符
void close() {
if (_fd != -1) {
// Ensure unmapped before closing the fd.
// Although POSIX states munmap does not close fd, it's good practice
// to unmap before closing if the map covered the whole file.
// If map only covered a portion, closing invalidates the map anyway.
// For simplicity in this full-file map case, ensure unmap first.
unmap(); // Unmap if it was mapped
final result = _closeFile(_fd);
if (result < 0) {
print('Error closing file: $path');
// Similar to unmap, print error.
}
_fd = -1;
_fileSize = -1;
} else {
print('Warning: File is not currently open.');
}
}
/// 释放所有资源 (unmap and close)
void dispose() {
unmap();
close();
}
}
// Example of using MmapFile:
/*
Future<void> readLargeFileWithMmap(String filePath) async {
final mmapFile = MmapFile(filePath);
try {
await mmapFile.open();
final fileSize = mmapFile.fileSize;
print('File opened. Size: $fileSize bytes');
if (fileSize > 0) {
final mappedView = mmapFile.map();
print('File mapped to memory.');
// Access data using the mappedView (Uint8List)
// This is the zero-copy part!
if (mappedView.isNotEmpty) {
print('First 10 bytes: ${mappedView.sublist(0, mappedView.length > 10 ? 10 : mappedView.length)}');
}
// When done, unmap the memory
mmapFile.unmap();
print('Memory unmapped.');
}
} catch (e) {
print('Error reading file with mmap: $e');
} finally {
// Always close the file descriptor
mmapFile.close();
print('File descriptor closed.');
}
}
*/
5. Dart Demo App (lib/main.dart)
创建一个简单的 UI 来生成文件并使用 MmapFile 读取它。
import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';
import 'dart:io';
import 'dart:typed_data';
import 'dart:convert'; // For utf8 encoding/decoding
import 'mmap_util.dart'; // Import our mmap utility
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'FFI mmap Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(title: 'FFI mmap Demo'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
String _status = 'Idle';
String _fileContent = '';
bool _isProcessing = false;
static const String _testFileName = 'large_test_file.txt';
static const int _fileSizeMB = 10; // File size in MB for demo
Future<String> _getFilePath() async {
final directory = await getApplicationDocumentsDirectory();
return '${directory.path}/$_testFileName';
}
Future<void> _generateLargeFile() async {
setState(() {
_status = 'Generating file...';
_isProcessing = true;
});
try {
final filePath = await _getFilePath();
final file = File(filePath);
final sink = file.openWrite();
// Write 1MB blocks repeatedly
final data = Uint8List(_fileSizeMB * 1024 * 1024 ~/ 100); // Write in 10KB chunks
final chunk = utf8.encode('This is a test string for the large file mmap demo.' * 100); // Repeat a string
for(int i = 0; i < data.length; i += chunk.length) {
data.setRange(i, i + chunk.length, chunk);
}
// Write the large data chunk
for(int i = 0; i < 100; i++) { // Repeat 100 times to get 10MB
sink.writeBytesSync(data);
}
await sink.close();
setState(() {
_status = 'File "$_testFileName" (${_fileSizeMB}MB) generated at $filePath';
});
} catch (e) {
setState(() {
_status = 'Error generating file: $e';
});
} finally {
setState(() {
_isProcessing = false;
});
}
}
Future<void> _readWithMmap() async {
setState(() {
_status = 'Reading file with mmap...';
_isProcessing = true;
_fileContent = '';
});
final filePath = await _getFilePath();
final mmapFile = MmapFile(filePath); // Create MmapFile instance
try {
// 1. Open the file
await mmapFile.open();
final fileSize = mmapFile.fileSize;
setState(() {
_status = 'File opened. Size: $fileSize bytes. Mapping...';
});
if (fileSize > 0) {
// 2. Map the file
final mappedView = mmapFile.map();
setState(() {
_status = 'File mapped to memory.';
});
// 3. Access data directly from the mapped memory (Uint8List view)
// This is zero-copy. We only read a small part for display.
final bytesToRead = 200; // Read first 200 bytes
final actualBytesRead = mappedView.length < bytesToRead ? mappedView.length : bytesToRead;
final contentBytes = mappedView.sublist(0, actualBytesRead);
final contentString = utf8.decode(contentBytes, allowMalformed: true); // Decode as UTF8
setState(() {
_fileContent = 'Read $actualBytesRead bytes:\n$contentString...';
_status = 'Successfully read $actualBytesRead bytes using mmap.';
});
// 4. Unmap the memory when done accessing the mappedView
mmapFile.unmap();
setState(() {
_status += '\nMemory unmapped.';
});
} else {
setState(() {
_fileContent = 'File is empty, nothing to read.';
_status = 'File is empty.';
});
}
} catch (e) {
setState(() {
_status = 'Error reading file with mmap: $e';
_fileContent = 'Error: $e';
});
print('Error details: $e');
} finally {
// 5. Close the file descriptor
mmapFile.dispose(); // Calls unmap() if needed and then close()
setState(() {
_status += '\nResources disposed (unmapped and closed fd).';
_isProcessing = false;
});
}
}
Future<void> _deleteFile() async {
setState(() {
_status = 'Deleting file...';
_isProcessing = true;
});
try {
final filePath = await _getFilePath();
final file = File(filePath);
if (await file.exists()) {
await file.delete();
setState(() {
_status = 'File "$_testFileName" deleted.';
_fileContent = '';
});
} else {
setState(() {
_status = 'File "$_testFileName" does not exist.';
});
}
} catch (e) {
setState(() {
_status = 'Error deleting file: $e';
});
} finally {
setState(() {
_isProcessing = false;
});
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Center(
child: SingleChildScrollView(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
ElevatedButton(
onPressed: _isProcessing ? null : _generateLargeFile,
child: const Text('Generate 10MB Test File'),
),
const SizedBox(height: 12),
ElevatedButton(
onPressed: _isProcessing ? null : _readWithMmap,
child: const Text('Read File with mmap (Zero-Copy)'),
),
const SizedBox(height: 12),
ElevatedButton(
onPressed: _isProcessing ? null : _deleteFile,
child: const Text('Delete Test File'),
style: ElevatedButton.styleFrom(backgroundColor: Colors.redAccent),
),
const SizedBox(height: 24),
const Text('Status:', style: TextStyle(fontWeight: FontWeight.bold)),
Text(_status),
const SizedBox(height: 24),
const Text('File Content (first 200 bytes):', style: TextStyle(fontWeight: FontWeight.bold)),
Container(
padding: const EdgeInsets.all(8),
decoration: BoxDecoration(
border: Border.all(color: Colors.grey),
borderRadius: BorderRadius.circular(4),
),
child: Text(_fileContent),
),
],
),
),
),
),
);
}
}
构建和运行:
- 准备 C 文件:
- 将
c/mmap_helper.c 和 c/mmap_helper.h 复制到 android/src/main/cpp/ 目录。
- 在 Xcode 中打开
ios/Runner.xcworkspace,将 c/mmap_helper.c 和 c/mmap_helper.h 添加到 Runner target 的 Compile Sources 和 Headers 中。
- 获取依赖: 在项目根目录运行
flutter pub get。
- 运行应用: 连接 Android 设备/模拟器 或 iOS 设备/模拟器,然后运行
flutter run。
说明:
- 零拷贝: 当你调用
mmapFile.map() 并得到 Uint8List mappedView 时,mappedView 不是一个独立的数据拷贝。它是一个直接指向内核为你映射的内存区域的视图。访问 mappedView 中的数据就是直接访问那块共享内存,而不是将文件内容复制到 Dart/Flutter 堆中。
- 资源管理:
mmap 和文件描述符是本地资源,必须显式释放 (munmap 和 close)。MmapFile.dispose() 方法封装了这个过程,在不再需要文件访问时务必调用它。使用 try...catch...finally 结构可以帮助确保在发生错误时也能释放资源。
- 错误处理: 示例中包含了基本的错误检查(检查 FFI 返回值是否是错误指示符),并抛出 Dart 异常。实际应用中可能需要更健壮的错误报告机制。
- 文件路径:
path_provider 用于获取应用沙盒内的目录,这样读写文件通常不需要额外的存储权限。
- 大文件: 示例生成一个 10MB 的文件。你可以尝试更大的文件来观察
mmap 的效果(例如,即使是几十或几百兆的文件,读取开头部分的速度也应该非常快,因为只映射了文件的一部分或按需加载)。
这个示例提供了使用 Dart FFI 调用 mmap 的基础框架。对于更高级的用例,你可能需要处理:
- 映射文件的部分区域(通过调整
offset 和 length)。
- 写入映射的内存区域(需要
PROT_WRITE 和 MAP_SHARED,并考虑同步问题)。
- 处理文件截断或其他文件系统事件。
- 在 Dart 中实现更复杂的同步原语。