A series of simple examples demonstrating how to call C libraries from Dart.
Please note that the Dart FFI API is in active development and likely to change before release. This code is designed to work with Dart version 2.5.0.
The C make files are (currently) written to work on a Mac. To compile the
libraries, go to the c/ folder in each subproject and run:
make dylibA .dylib file should be created in the parent folder. Navigate to that and run the dart file.
On Windows:
A dll can be created in two ways.
-
Using
gccIn the subproject's
c/runmake dll
Install gcc from msys2, a more detailed tutorial.
And add it to
patheg:C:\msys64\mingw64\bin\.And make sure
gcc -dumpmachinegives something likex86_64-w64-mingw32but NOTi686-w64-mingw32eg:C:\msys64\mingw64\bin\gcc.exe -
Using
clfrom the Visual Studio build. Follow the docs to be able to runnmake.exefrom cmd line.- Visual Studio needs to be installed with c/c++ checked.
- Then add
\path\to\VC\Auxiliary\BuildtoPATHeg:C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Auxiliary\Build - You can now run
vcvars32.bat,vcvars64.bat,vcvarsx86_amd64.batetc.from the command line as mentioned in the docs. - Then choose your setup and run
vcvars*.batand now,cl.exe,nmake.execan be used from the command line.
In the subproject's
c/runnmake -f Nmakefile dll
A .dll file should be created in the parent folder. Navigate to that and run the dart file.
Only applicable if on Windows:
The c/c++ functions should be exported or dart will not be able to lookup the function definitions.
This can be done in two ways.
-
Using the keyword
__declspec(dllexport)in the class/function's definition docs -
Creating a
.deffile docs
In every subproject's
c/directory there is.deffile.That might be neccessary (depending on whether the functions were already exported) to create a dynamic link library
dllon Windows. As it's used to define what functions are to be exported when creating a dll.More details on how to write/generate one here
Samples with a Dockerfile can be tested using Docker:
docker build -t dart-ffi .
docker run dart-ffi pub run test