Loading repository data…
Loading repository data…
devmuaz / repository
A Dart console application that demonstrates Foreign Function Interface (FFI) by reading text files using native macOS APIs.
A Dart console application that demonstrates Foreign Function Interface (FFI) by reading text files using native C APIs. This project showcases how to bridge Dart and C code to perform file I/O operations using low-level POSIX system calls.
You can read the full toturial article on my Medium: Beyond Dart: Tapping into C's Power with FFI
open, read, fstat) for file operationsdart:ffiaccess() system calldart_io_ffi/
├── bin/
│ └── main.dart # Main application entry point
├── lib/
│ └── native_file_reader.dart # Dart FFI wrapper class
├── native/
│ ├── file_reader.c # C implementation of file operations
│ ├── file_reader.h # C header file with function declarations
│ └── build/
│ └── libfile_reader.dylib # Compiled shared library
├── build.sh # Build script for the native library
├── pubspec.yaml # Dart package configuration
└── README.md # This file
First, compile the C code into a shared library:
./build.sh
This will create native/build/libfile_reader.dylib on macOS.
dart pub get
dart run bin/main.dart <file_path>
Example:
dart run bin/main.dart README.md
dart run bin/main.dart pubspec.yaml
native/file_reader.c)The C code provides three main functions:
read_file(const char *file_path): Opens a file, reads its contents, and returns a malloc'd stringfile_exists(const char *file_path): Checks if a file exists using the access() system callfree_string(char *str): Properly frees memory allocated by read_filelib/native_file_reader.dart)The NativeFileReader class:
bin/main.dart)typedef ReadFileC = Pointer<Utf8> Function(Pointer<Utf8>);
typedef FileExistsC = Int32 Function(Pointer<Utf8>);
typedef FreeStringC = Void Function(Pointer<Utf8>);
malloc()free_string()finally blocksThe application handles various error conditions:
.dylib shared libraries.so shared libraries.dll dynamic librariesTo adapt for other platforms, modify the library extension in _getLibraryPath() and update the build script accordingly.