This is the second day of my participation in the November Gwen Challenge. Check out the details: the last Gwen Challenge 2021

Dart FFI provides a number of methods for connecting Dart and C. Here are the main ones.

Load the library

DynamicLibrary.open

It can load dynamic link libraries

external factory DynamicLibrary.open(String path);
Copy the code

This method is used to load library files, like the libsample.1.0.0.dylib file I generated after compiling C in the previous article, and we need to use this method to load it into DartVM. Note that calling this method multiple times to load the library file will only load the library file into DartVM once.

Example:

import 'dart:ffi' as ffi;
import 'package:path/path.dart' as path;
var libraryPath = path.join(
        Directory.current.path, 'library'.'build'.'libsample.dylib');
final dylib = ffi.DynamicLibrary.open(libraryPath);
Copy the code

DynamicLibrary.process

external factory DynamicLibrary.process();
Copy the code

It can be used to load dynamic link libraries that an application has automatically loaded in iOS and MacOS, and it can resolve binary symbols that are statically linked to an application. It is important to note that it is not available on Windows platforms

DynamicLibrary.executable

external factory DynamicLibrary.executable();
Copy the code

It can be used to load statically linked libraries

NativeType

NativeType represents data structures in C in Dart, which I’ll share in the next article. It cannot be instantiated in Dart and can only be returned by Native.

Pointer

It is a mapping of Pointers in C to Dart

DynamicLibrary->lookup()

external Pointer<T> lookup<T extends NativeType>(String symbolName);
Copy the code

It is used to find the corresponding symbol in the DynamicLibrary and return its memory address.

Dart usage:

final dylib = DynamicLibrary.open(libraryPath);
late final _hello_worldPtr =
      dylib.lookup<NativeFunction<Void Function() > > ('hello_world');
late final _hello_world = _hello_worldPtr.asFunction<void Function(a) > (); _hello_world();Copy the code

Pointer.fromAddress(int ptr)

Gets C object Pointers based on memory addresses

Such as:

// Create a Native pointer to NULL
final Pointer<Never> nullptr = Pointer.fromAddress(0);
Copy the code

Pointer.fromFunction

From a Dart function, create a pointer to a Native function. This pointer is usually used to pass the Dart function to C so that C can call the Dart function

void globalCallback(int src, int result) {
   print("globalCallback src=$src, result=$result");
}
Pointer.fromFunction(globalCallback);)
Copy the code

Pointer->address()

Gets the memory address of the pointer

asFunction

Convert Native pointer objects into Dart functions

conclusion

Dart FFI: Dart FFI: Dart FFI: Dart FFI I will continue to explain the mapping between Dart and C data structures, so please pay attention.

Making the warehouse