CodeBlanks Logo Icon CodeBlanks

DynamicLibrary

Learn native loading with DynamicLibrary.

DynamicLibrary

DynamicLibrary is the dart:ffi class that represents C libraries on the Dart side. A library is loaded from a file with DynamicLibrary.open('libmylib.so'), from the process with DynamicLibrary.process(), or from the executable with DynamicLibrary.executable().

The opened library is a handle; symbols (functions) are looked up via lookupFunction. If the library cannot be loaded, an ArgumentError is thrown. The file extension depends on the platform: Linux .so, macOS .dylib, Windows .dll.

Symbol lookup

Once a DynamicLibrary is loaded, its functions are looked up with lookupFunction. Each function is represented by a symbol name; for example, add may be int add(int, int) on the C side.

If a symbol is not found, an ArgumentError is thrown. FFI maps between native and Dart types: Int32 ↔ int, Double ↔ double, Pointer<Void> ↔ Pointer<NativeType>. The mapping is declared statically.

Practice A LibraryLoader class

Define a LibraryLoader class with final String path; final String platform; LibraryLoader(this.path, this.platform); field and constructor. Add a String describe() => 'loading $path on $platform'; method. In main create final l = LibraryLoader('libmylib.so', 'Linux');; print with print(l.describe());.

Starter code

main.dart
void main() {
  // define a LibraryLoader class (path, platform; describe)
  // create a LibraryLoader; print describe()
}

Sample solution

main.dart
class LibraryLoader {
  final String path;
  final String platform;
  LibraryLoader(this.path, this.platform);
  String describe() => 'loading $path on $platform';
}

void main() {
  final l = LibraryLoader('libmylib.so', 'Linux');
  print(l.describe());
}

Expected output

loading libmylib.so on Linux

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Library loading

Question
final lib = DynamicLibrary.____('libmylib.so');
Answer
final lib = DynamicLibrary.open('libmylib.so');

Explanation: DynamicLibrary.open loads a C library from a file.

2 What is the file extension of a C library on Linux?

  • .dll
  • .dylib
  • .so Correct answer
  • .exe

Explanation: on Linux, C libraries use the .so extension.

3 Match the DynamicLibrary methods

Term Meaning
DynamicLibrary.open Load from file
DynamicLibrary.process Load from process
DynamicLibrary.executable From executable
lookupFunction Symbol lookup

All lessons in Expert