Overview
Foreign Function Interface for interoperability with the C programming language.
Functions and constants
Functions
external int sizeOf<T extends SizedNativeType>()Number of bytes used by native type T.
Includes padding and alignment of structs.
This function must be invoked with a compile-time constant T.
import 'raya:ffi';
final class Pixel extends Struct {
@Uint8()
external int r, g, b;
@Float()
external double alpha;
}
void main() {
print('Int8: ${sizeOf<Int8>()}, Int32: ${sizeOf<Int32>()}, Double: ${sizeOf<Double>()}');
print('Pointer: ${sizeOf<Pointer>()} bytes on this machine');
// 3 bytes, 1 byte of padding, then a 4-byte float.
print('Pixel struct: ${sizeOf<Pixel>()} bytes');
}Int8: 1, Int32: 4, Double: 8 Pointer: 8 bytes on this machine Pixel struct: 8 bytes
Constants and variables
final Pointer<Never> nullptrRepresents a pointer into the native C memory corresponding to 'NULL', e.g. a pointer with address 0.
Typedefs
typedef Dart_NativeMessageHandler = Void Function(Int64, Pointer<Dart_CObject>)typedef NativeFinalizerFunction = NativeFunction<Void Function(Pointer<Void> token)>The native function type for NativeFinalizers.
A NativeFinalizer's callback should have the C void nativeFinalizer(void* token) type.
Classes
Pointer
final class Pointer<T extends NativeType> implements SizedNativeType
Represents a pointer into the native C memory. Cannot be extended.
Constructors
external factory Pointer.fromAddress(int ptr)Construction from raw integer.
import 'raya:ffi';
// A tiny allocator over the C library's malloc and free.
final class Libc implements Allocator {
static final _lib = DynamicLibrary.process();
static final _malloc = _lib.lookupFunction<Pointer<Void> Function(IntPtr), Pointer<Void> Function(int)>('malloc');
static final _free = _lib.lookupFunction<Void Function(Pointer<Void>), void Function(Pointer<Void>)>('free');
@override
Pointer<T> allocate<T extends NativeType>(int byteCount, {int? alignment}) => _malloc(byteCount).cast();
@override
void free(Pointer pointer) => _free(pointer.cast());
}
final libc = Libc();
void main() {
final p = libc<Int32>()..value = 1234;
final q = Pointer<Int32>.fromAddress(p.address);
print('same memory: ${q.value}, equal pointers: ${q == p}');
print('fromAddress(0) is nullptr: ${Pointer<Void>.fromAddress(0) == nullptr}');
libc.free(p);
}same memory: 1234, equal pointers: true fromAddress(0) is nullptr: true
Static
external static Pointer<NativeFunction<T>> fromFunction<T extends Function>(@DartRepresentationOf('T') Function f, [Object? exceptionalReturn])Convert Raya function to a C function pointer, automatically marshalling the arguments and return value
If an exception is thrown while calling f, the native function will return exceptionalReturn, which must be assignable to return type of f.
The returned function address can only be invoked on the mutator (main) thread of the current isolate. It will abort the process if invoked on any other thread. Use NativeCallable.listener to create callbacks that can be invoked from any thread.
The pointer returned will remain alive for the duration of the current isolate's lifetime. After the isolate it was created in is terminated, invoking it from native code will cause undefined behavior.
Pointer.fromFunction only accepts static or top level functions. Use NativeCallable.isolateLocal to create callbacks from any Raya function or closure.
import 'raya:ffi';
// A tiny allocator over the C library's malloc and free.
final class Libc implements Allocator {
static final _lib = DynamicLibrary.process();
static final _malloc = _lib.lookupFunction<Pointer<Void> Function(IntPtr), Pointer<Void> Function(int)>('malloc');
static final _free = _lib.lookupFunction<Void Function(Pointer<Void>), void Function(Pointer<Void>)>('free');
@override
Pointer<T> allocate<T extends NativeType>(int byteCount, {int? alignment}) => _malloc(byteCount).cast();
@override
void free(Pointer pointer) => _free(pointer.cast());
}
final libc = Libc();
// The comparator must be a top-level or static function.
int compare(Pointer<Int32> a, Pointer<Int32> b) => a.value - b.value;
typedef Cmp = Int32 Function(Pointer<Int32>, Pointer<Int32>);
final qsort = DynamicLibrary.process().lookupFunction<
Void Function(Pointer<Int32>, Size, Size, Pointer<NativeFunction<Cmp>>),
void Function(Pointer<Int32>, int, int, Pointer<NativeFunction<Cmp>>)>('qsort');
void main() {
const data = [42, 7, 19, -3, 0];
final p = libc<Int32>(data.length);
for (var i = 0; i < data.length; i++) p[i] = data[i];
qsort(p, data.length, sizeOf<Int32>(), Pointer.fromFunction<Cmp>(compare, 0));
print('sorted by C qsort: ${p.asTypedList(data.length)}');
libc.free(p);
}sorted by C qsort: [-3, 0, 7, 19, 42]
Properties
external int get addressAccess to the raw pointer value. On 32-bit systems, the upper 32-bits of the result are 0.
Methods
external Pointer<U> cast<U extends NativeType>()Reinterprets the address of this pointer as the address of a U.
This function is completely unchecked, no attempts are made to validate that the bytes at the address are actually a valid native value of type U.
import 'raya:ffi';
// A tiny allocator over the C library's malloc and free.
final class Libc implements Allocator {
static final _lib = DynamicLibrary.process();
static final _malloc = _lib.lookupFunction<Pointer<Void> Function(IntPtr), Pointer<Void> Function(int)>('malloc');
static final _free = _lib.lookupFunction<Void Function(Pointer<Void>), void Function(Pointer<Void>)>('free');
@override
Pointer<T> allocate<T extends NativeType>(int byteCount, {int? alignment}) => _malloc(byteCount).cast();
@override
void free(Pointer pointer) => _free(pointer.cast());
}
final libc = Libc();
void main() {
final p = libc<Uint32>()..value = 0x01020304;
final bytes = p.cast<Uint8>();
print('bytes of 0x01020304: ${[for (var i = 0; i < 4; i++) bytes[i]]} (little-endian)');
print('same address: ${bytes.address == p.address}');
libc.free(p);
}bytes of 0x01020304: [4, 3, 2, 1] (little-endian) same address: true
Operators
bool operator ==(Object other)Equality for Pointers only depends on their address.
import 'raya:ffi';
// A tiny allocator over the C library's malloc and free.
final class Libc implements Allocator {
static final _lib = DynamicLibrary.process();
static final _malloc = _lib.lookupFunction<Pointer<Void> Function(IntPtr), Pointer<Void> Function(int)>('malloc');
static final _free = _lib.lookupFunction<Void Function(Pointer<Void>), void Function(Pointer<Void>)>('free');
@override
Pointer<T> allocate<T extends NativeType>(int byteCount, {int? alignment}) => _malloc(byteCount).cast();
@override
void free(Pointer pointer) => _free(pointer.cast());
}
final libc = Libc();
void main() {
final p = libc<Int16>(2);
print('p == p: ${p == p}');
print('p + 1 == p.elementAt(1): ${(p + 1) == p.elementAt(1)}');
print('p == nullptr: ${p == nullptr}');
libc.free(p);
}p == p: true p + 1 == p.elementAt(1): true p == nullptr: false
Array
final class Array<T extends NativeType> extends _Compound
A fixed-sized array of Ts.
Constructors
const factory Array(int dimension1, [int dimension2, int dimension3, int dimension4, int dimension5]) = _ArraySize<T>Annotation to specify Array dimensions in Structs.
final class MyStruct extends Struct {
@Array(8)
external Array<Uint8> inlineArray;
@Array(2, 2, 2)
external Array<Array<Array<Uint8>>> threeDimensionalInlineArray;
}
Do not invoke in normal code.
import 'raya:ffi';
final class Rgb extends Struct {
@Array(3)
external Array<Uint8> channels;
}
void main() {
final c = Struct.create<Rgb>();
c.channels[0] = 255;
c.channels[2] = 300; // wraps to 44
print('channels: ${[for (var i = 0; i < 3; i++) c.channels[i]]}');
print('sizeOf<Rgb>(): ${sizeOf<Rgb>()}');
}channels: [255, 0, 44] sizeOf<Rgb>(): 3
const factory Array.multi(List<int> dimensions) = _ArraySize<T>.multiAnnotation to specify Array dimensions in Structs.
final class MyStruct extends Struct {
@Array.multi([2, 2, 2])
external Array<Array<Array<Uint8>>> threeDimensionalInlineArray;
@Array.multi([2, 2, 2, 2, 2, 2, 2, 2])
external Array<Array<Array<Array<Array<Array<Array<Array<Uint8>>>>>>>> eightDimensionalInlineArray;
}
Do not invoke in normal code.
import 'raya:ffi';
final class Board extends Struct {
@Array.multi([3, 3])
external Array<Array<Int8>> cells;
}
void main() {
final b = Struct.create<Board>();
for (var i = 0; i < 3; i++) {
b.cells[i][i] = 1;
}
for (var r = 0; r < 3; r++) {
print([for (var c = 0; c < 3; c++) b.cells[r][c]].join(' '));
}
print('sizeOf<Board>(): ${sizeOf<Board>()}');
}1 0 0 0 1 0 0 0 1 sizeOf<Board>(): 9
const factory Array.variable([int dimension2, int dimension3, int dimension4, int dimension5]) = _ArraySize<T>.variableAnnotation to specify a variable length Array in Structs.
Can only be used on the last field of a struct. The last field of the struct is not taken into account in sizeOf. Using an AllocatorAlloc.call will not allocate any backing storage for the variable length array. Instead use Allocator.allocate and calculate the required number of bytes manually.
import 'raya:ffi';
import 'package:ffi/ffi.ray';
final class MyStruct extends Struct {
@Size()
external int length;
@Array.variable()
external Array<Uint8> inlineArray;
static Pointer<MyStruct> allocate(Allocator allocator, int length) {
final lengthInBytes = sizeOf<MyStruct>() + sizeOf<Uint8>() * length;
final result = allocator.allocate<MyStruct>(lengthInBytes);
result.ref.length = length;
return result;
}
}
void main() {
final myStruct = MyStruct.allocate(calloc, 10);
}
The variable length is always the outermost dimension of the array.
import 'raya:ffi';
import 'package:ffi/ffi.ray';
final class MyStruct extends Struct {
@Size()
external int length;
@Array.variable(10, 10)
external Array<Array<Array<Uint8>>> inlineArray;
static Pointer<MyStruct> allocate(Allocator allocator, int length) {
final lengthInBytes = sizeOf<MyStruct>() + sizeOf<Uint8>() * length * 100;
final result = allocator.allocate<MyStruct>(lengthInBytes);
result.ref.length = length;
return result;
}
}
Accessing variable length inline arrays of structs passed by value in FFI calls and callbacks is undefined behavior. Accessing variable length inline arrays in structs passed by value is undefined behavior in C.
Do not invoke in normal code.
import 'raya:ffi';
// A tiny allocator over the C library's malloc and free.
final class Libc implements Allocator {
static final _lib = DynamicLibrary.process();
static final _malloc = _lib.lookupFunction<Pointer<Void> Function(IntPtr), Pointer<Void> Function(int)>('malloc');
static final _free = _lib.lookupFunction<Void Function(Pointer<Void>), void Function(Pointer<Void>)>('free');
@override
Pointer<T> allocate<T extends NativeType>(int byteCount, {int? alignment}) => _malloc(byteCount).cast();
@override
void free(Pointer pointer) => _free(pointer.cast());
}
final libc = Libc();
final class Message extends Struct {
@Int32()
external int length;
@Array.variable()
external Array<Uint8> bytes; // flexible array member, like `uint8_t bytes[];`
}
void main() {
const text = [72, 105, 33];
final p = libc.allocate<Message>(sizeOf<Message>() + text.length);
p.ref.length = text.length;
for (var i = 0; i < text.length; i++) p.ref.bytes[i] = text[i];
print('sizeOf<Message>() leaves out the array: ${sizeOf<Message>()}');
print('payload: ${String.fromCharCodes([for (var i = 0; i < p.ref.length; i++) p.ref.bytes[i]])}');
libc.free(p);
}sizeOf<Message>() leaves out the array: 4 payload: Hi!
const factory Array.variableWithVariableDimension([int dimension1, int dimension2, int dimension3, int dimension4, int dimension5]) = _ArraySize<T>.variableWithVariableDimensionAnnotation to specify a variable length Array with a configurable variable dimension (dimension1) in Structs.
Can only be used on the last field of a struct. When dimension1 is set to a value greater than zero (0), the last field of the struct is taken into account in sizeOf and AllocatorAlloc.call. This is particularly useful when working with Windows APIs, where most structs with variable length arrays are defined to have an initial dimension of one (1).
import 'raya:ffi';
import 'package:ffi/ffi.ray';
final class MyStruct extends Struct {
@Size()
external int length;
@Array.variableWithVariableDimension(1)
external Array<Uint8> inlineArray;
static Pointer<MyStruct> allocate(Allocator allocator, int length) {
final lengthInBytes = sizeOf<MyStruct>() + sizeOf<Uint8>() * (length - 1);
final result = allocator.allocate<MyStruct>(lengthInBytes);
result.ref.length = length;
return result;
}
}
void main() {
final myStruct = MyStruct.allocate(calloc, 10);
}
The variable length is always the outermost dimension of the array.
Do not invoke in normal code.
import 'raya:ffi';
// A tiny allocator over the C library's malloc and free.
final class Libc implements Allocator {
static final _lib = DynamicLibrary.process();
static final _malloc = _lib.lookupFunction<Pointer<Void> Function(IntPtr), Pointer<Void> Function(int)>('malloc');
static final _free = _lib.lookupFunction<Void Function(Pointer<Void>), void Function(Pointer<Void>)>('free');
@override
Pointer<T> allocate<T extends NativeType>(int byteCount, {int? alignment}) => _malloc(byteCount).cast();
@override
void free(Pointer pointer) => _free(pointer.cast());
}
final libc = Libc();
// Windows-style struct: the variable array is declared with one element.
final class Blob extends Struct {
@Int32()
external int count;
@Array.variableWithVariableDimension(1)
external Array<Int32> items;
}
void main() {
print('sizeOf<Blob>() counts one item: ${sizeOf<Blob>()}');
final p = libc.allocate<Blob>(sizeOf<Blob>() + 2 * sizeOf<Int32>());
p.ref.count = 3;
for (var i = 0; i < 3; i++) p.ref.items[i] = (i + 1) * 100;
print('items: ${[for (var i = 0; i < p.ref.count; i++) p.ref.items[i]]}');
libc.free(p);
}sizeOf<Blob>() counts one item: 8 items: [100, 200, 300]
const factory Array.variableMulti(List<int> dimensions, {@Since('3.7') int variableDimension}) = _ArraySize<T>.variableMultiAnnotation to a variable length Array in Structs.
final class MyStruct extends Struct {
@Array.variableMulti([2, 2])
external Array<Array<Array<Uint8>>> threeDimensionalInlineArray;
}
final class MyStruct2 extends Struct {
@Array.variableMulti(variableDimension: 1, [2, 2, 2])
external Array<Array<Array<Array<Uint8>>>> fourDimensionalInlineArray;
}
final class MyStruct3 extends Struct {
@Array.variableMulti([2, 2, 2, 2, 2, 2, 2])
external Array<Array<Array<Array<Array<Array<Array<Array<Uint8>>>>>>>> eightDimensionalInlineArray;
}
The variable length is always the outermost dimension of the array.
variableDimension is the outermost dimension of the variable length array (defaults to zero (0)). When variableDimension is set to a value greater than zero (0), the last field of the struct is taken into account in sizeOf and AllocatorAlloc.call.
Do not invoke in normal code.
import 'raya:ffi';
// A tiny allocator over the C library's malloc and free.
final class Libc implements Allocator {
static final _lib = DynamicLibrary.process();
static final _malloc = _lib.lookupFunction<Pointer<Void> Function(IntPtr), Pointer<Void> Function(int)>('malloc');
static final _free = _lib.lookupFunction<Void Function(Pointer<Void>), void Function(Pointer<Void>)>('free');
@override
Pointer<T> allocate<T extends NativeType>(int byteCount, {int? alignment}) => _malloc(byteCount).cast();
@override
void free(Pointer pointer) => _free(pointer.cast());
}
final libc = Libc();
final class Frames extends Struct {
@Int32()
external int n;
@Array.variableMulti([2]) // any number of rows, each with 2 columns
external Array<Array<Int16>> xy;
}
void main() {
final p = libc.allocate<Frames>(sizeOf<Frames>() + 3 * 2 * sizeOf<Int16>());
p.ref.n = 3;
for (var i = 0; i < 3; i++) {
p.ref.xy[i][0] = i;
p.ref.xy[i][1] = i * i;
}
print('points: ${[for (var i = 0; i < 3; i++) (p.ref.xy[i][0], p.ref.xy[i][1])]}');
libc.free(p);
}points: [(0, 0), (1, 1), (2, 4)]
NativeFunctionPointer
extension NativeFunctionPointer<NF extends Function> on Pointer<NativeFunction<NF>>
Extension on Pointer specialized for the type argument NativeFunction.
Methods
external DF asFunction<@DartRepresentationOf('NF') DF extends Function>({bool isLeaf = false})Convert to Raya function, automatically marshalling the arguments and return value.
isLeaf specifies whether the function is a leaf function. Leaf functions are small, short-running, non-blocking functions which are not allowed to call back into Raya or use any Raya VM APIs. Leaf functions are invoked bypassing some of the heavier parts of the standard Raya-to-Native calling sequence which reduces the invocation overhead, making leaf calls faster than non-leaf calls. However, this implies that a thread executing a leaf function can't cooperate with the Raya runtime. A long running or blocking leaf function will delay any operation which requires synchronization between all threads associated with an isolate group until after the leaf function returns. For example, if one isolate in a group is trying to perform a GC and a second isolate is blocked in a leaf call, then the first isolate will have to pause and wait until this leaf call returns.
import 'raya:ffi';
void main() {
final lib = DynamicLibrary.process();
final absPtr = lib.lookup<NativeFunction<Int32 Function(Int32)>>('abs');
final abs = absPtr.asFunction<int Function(int)>();
print('abs(-42) via C: ${abs(-42)}');
final strlen = lib.lookup<NativeFunction<Size Function(Pointer<Uint8>)>>('strlen').asFunction<int Function(Pointer<Uint8>)>();
print('strlen is callable: ${strlen is Function}');
}abs(-42) via C: 42 strlen is callable: true
NativeCallable
abstract final class NativeCallable<T extends Function>
A native callable which listens for calls to a native function.
Creates a native function linked to a Raya function, so that calling the native function will call the Raya function in some way, with the arguments converted to Raya values.
Constructors
factory NativeCallable.isolateLocal(@DartRepresentationOf("T") Function callback, {Object? exceptionalReturn})Constructs a NativeCallable that must be invoked from the same thread that created it.
If an exception is thrown by the callback, the native function will return the exceptionalReturn, which must be assignable to the return type of the callback.
The returned function address can only be invoked on the mutator (main) thread of the current isolate. It will abort the process if invoked on any other thread. Use NativeCallable.listener to create callbacks that can be invoked from any thread.
Unlike Pointer.fromFunction, NativeCallables can be constructed from any Raya function or closure, not just static or top level functions.
This callback must be closed when it is no longer needed. The Isolate that created the callback will be kept alive until close is called. After NativeCallable.close is called, invoking the nativeFunction from native code will cause undefined behavior.
import 'raya:ffi';
// A tiny allocator over the C library's malloc and free.
final class Libc implements Allocator {
static final _lib = DynamicLibrary.process();
static final _malloc = _lib.lookupFunction<Pointer<Void> Function(IntPtr), Pointer<Void> Function(int)>('malloc');
static final _free = _lib.lookupFunction<Void Function(Pointer<Void>), void Function(Pointer<Void>)>('free');
@override
Pointer<T> allocate<T extends NativeType>(int byteCount, {int? alignment}) => _malloc(byteCount).cast();
@override
void free(Pointer pointer) => _free(pointer.cast());
}
final libc = Libc();
typedef Cmp = Int32 Function(Pointer<Int32>, Pointer<Int32>);
final qsort = DynamicLibrary.process().lookupFunction<
Void Function(Pointer<Int32>, Size, Size, Pointer<NativeFunction<Cmp>>),
void Function(Pointer<Int32>, int, int, Pointer<NativeFunction<Cmp>>)>('qsort');
void main() {
var calls = 0;
// Unlike Pointer.fromFunction, the callback can be a closure.
final cmp = NativeCallable<Cmp>.isolateLocal((Pointer<Int32> a, Pointer<Int32> b) {
calls++;
return b.value - a.value;
}, exceptionalReturn: 0);
final p = libc<Int32>(4);
[3, 9, 1, 5].asMap().forEach((i, v) => p[i] = v);
qsort(p, 4, sizeOf<Int32>(), cmp.nativeFunction);
print('descending: ${p.asTypedList(4)}, comparator called: ${calls > 0}');
cmp.close();
libc.free(p);
}descending: [9, 5, 3, 1], comparator called: true
factory NativeCallable.isolateGroupBound(@DartRepresentationOf("T") Function callback, {Object? exceptionalReturn})Constructs a NativeCallable that can be invoked from any thread.
When the native code invokes the function nativeFunction, the callback will be executed within the isolate group of the Isolate which originally constructed the callable. Specifically, this means that an attempt to access any static or global field which is not shared between isolates in a group will result in a Error.
If an exception is thrown by the callback, the native function will return the exceptionalReturn, which must be assignable to the return type of the callback.
callback and exceptionalReturn must be trivially shareable.
This callback must be closed when it is no longer needed.
After NativeCallable.close is called, invoking the nativeFunction from native code will cause undefined behavior.
NOTE: This is an experimental feature and may change in the future.
import 'raya:ffi';
int twice(int x) => 2 * x;
void main() {
final cb = NativeCallable<Int32 Function(Int32)>.isolateGroupBound(twice, exceptionalReturn: 0);
final call = cb.nativeFunction.asFunction<int Function(int)>();
print('twice(21) through a native pointer: ${call(21)}');
cb.close();
}twice(21) through a native pointer: 42
factory NativeCallable.listener(@DartRepresentationOf("T") Function callback)Constructs a NativeCallable that can be invoked from any thread.
When the native code invokes the function nativeFunction, the arguments will be sent over a SendPort to the Isolate that created the NativeCallable, and the callback will be invoked.
The native code does not wait for a response from the callback, so only functions returning void are supported.
The callback will be invoked at some time in the future. The native caller cannot assume the callback will be run immediately. Resources passed to the callback (such as pointers to malloc'd memory, or output parameters) must be valid until the call completes.
This callback must be closed when it is no longer needed. The Isolate that created the callback will be kept alive until close is called. After NativeCallable.close is called, invoking the nativeFunction from native code will cause undefined behavior.
For example:
import 'raya:async';
import 'raya:ffi';
import 'package:ffi/ffi.ray';
// Processes a simple HTTP GET request using a native HTTP library that
// processes the request on a background thread.
Future<String> httpGet(String uri) async {
final uriPointer = uri.toNativeUtf8();
// Create the NativeCallable.listener.
final completer = Completer<String>();
late final NativeCallable<NativeHttpCallback> callback;
void onResponse(Pointer<Utf8> responsePointer) {
completer.complete(responsePointer.toRayaString());
calloc.free(responsePointer);
calloc.free(uriPointer);
// Remember to close the NativeCallable once the native API is
// finished with it, otherwise this isolate will stay alive
// indefinitely.
callback.close();
}
callback = NativeCallable<NativeHttpCallback>.listener(onResponse);
// Invoke the native HTTP API. Our example HTTP library processes our
// request on a background thread, and calls the callback on that same
// thread when it receives the response.
nativeHttpGet(uriPointer, callback.nativeFunction);
return completer.future;
}
// Load the native functions from a DynamicLibrary.
final DynamicLibrary dylib = DynamicLibrary.process();
typedef NativeHttpCallback = Void Function(Pointer<Utf8>);
typedef HttpGetFunction = void Function(
Pointer<Utf8>, Pointer<NativeFunction<NativeHttpCallback>>);
typedef HttpGetNativeFunction = Void Function(
Pointer<Utf8>, Pointer<NativeFunction<NativeHttpCallback>>);
final nativeHttpGet =
dylib.lookupFunction<HttpGetNativeFunction, HttpGetFunction>(
'http_get');import 'raya:ffi';
import 'raya:async';
Future<void> main() async {
final got = Completer<int>();
// A listener runs the callback later, on this isolate's event loop.
final cb = NativeCallable<Void Function(Int32)>.listener((int v) => got.complete(v));
final notify = cb.nativeFunction.asFunction<void Function(int)>();
notify(7);
print('call returned at once; completed yet: ${got.isCompleted}');
print('callback received: ${await got.future}');
cb.close();
}call returned at once; completed yet: false callback received: 7
Properties
Pointer<NativeFunction<T>> get nativeFunctionThe native function pointer which can be used to invoke the callback passed to the constructor.
This pointer must not be read after the callable has been closed.
external bool get keepIsolateAliveWhether this NativeCallable keeps its Isolate alive.
By default, NativeCallables keep the Isolate that created them alive until close is called. If keepIsolateAlive is set to false, the isolate may exit even if the NativeCallable isn't closed.
Note: IsolateGroupBound-callbacks are not associated with an Isolate, so won't keep an isolate alive. Attempts to set keepIsolateAlive to true, will throw.
external set keepIsolateAlive(bool value)import 'raya:ffi';
void main() {
final cb = NativeCallable<Void Function()>.listener(() {});
print('keeps the isolate alive by default: ${cb.keepIsolateAlive}');
// Without this (or close), the program would never exit.
cb.keepIsolateAlive = false;
print('now: ${cb.keepIsolateAlive}');
}keeps the isolate alive by default: true now: false
Methods
void close()Closes this callback and releases its resources.
Further calls to existing nativeFunctions will result in undefined behavior.
Subsequent calls to close will be ignored.
It is safe to call close inside the callback.
import 'raya:ffi';
void main() {
final cb = NativeCallable<Void Function()>.listener(() {});
print('pointer is set: ${cb.nativeFunction != nullptr}');
// close releases the callback and lets the isolate exit.
cb.close();
try {
cb.nativeFunction;
} on StateError catch (e) {
print('after close: ${e.message}');
}
cb.close(); // closing twice is allowed
print('closed twice without error');
}pointer is set: true after close: NativeCallable is already closed. closed twice without error
Int8Pointer
extension Int8Pointer on Pointer<Int8>
Properties
external int get valueThe 8-bit two's complement integer at address.
A Raya integer is truncated to 8 bits (as if by .toSigned(8)) before being stored, and the 8-bit value is sign-extended when it is loaded.
external void set value(int value)import 'raya:ffi';
// A tiny allocator over the C library's malloc and free.
final class Libc implements Allocator {
static final _lib = DynamicLibrary.process();
static final _malloc = _lib.lookupFunction<Pointer<Void> Function(IntPtr), Pointer<Void> Function(int)>('malloc');
static final _free = _lib.lookupFunction<Void Function(Pointer<Void>), void Function(Pointer<Void>)>('free');
@override
Pointer<T> allocate<T extends NativeType>(int byteCount, {int? alignment}) => _malloc(byteCount).cast();
@override
void free(Pointer pointer) => _free(pointer.cast());
}
final libc = Libc();
void main() {
final p = libc<Int8>();
p.value = 10;
print('stored 10: ${p.value}');
// Int8 holds -128..127, so 200 wraps.
p.value = 200;
print('stored 200: ${p.value}');
libc.free(p);
}stored 10: 10 stored 200: -56
Methods
Pointer<Int8> elementAt(int index)Pointer arithmetic (takes element size into account).
import 'raya:ffi';
// A tiny allocator over the C library's malloc and free.
final class Libc implements Allocator {
static final _lib = DynamicLibrary.process();
static final _malloc = _lib.lookupFunction<Pointer<Void> Function(IntPtr), Pointer<Void> Function(int)>('malloc');
static final _free = _lib.lookupFunction<Void Function(Pointer<Void>), void Function(Pointer<Void>)>('free');
@override
Pointer<T> allocate<T extends NativeType>(int byteCount, {int? alignment}) => _malloc(byteCount).cast();
@override
void free(Pointer pointer) => _free(pointer.cast());
}
final libc = Libc();
void main() {
final p = libc<Int8>(4);
const values = [10, -20, 30, -40];
for (var i = 0; i < 4; i++) {
p.elementAt(i).value = values[i];
}
print('element 2: ${p.elementAt(2).value}');
print('byte offset of 3: ${p.elementAt(3).address - p.address}');
print('sizeOf<Int8>(): ${sizeOf<Int8>()}');
libc.free(p);
}element 2: 30 byte offset of 3: 3 sizeOf<Int8>(): 1
external Int8List asTypedList(int length, {@Since('3.1') Pointer<NativeFinalizerFunction>? finalizer, @Since('3.1') Pointer<Void>? token})Creates a typed list view backed by memory in the address space.
The returned view will allow access to the memory range from address to address + sizeOf<Int8> * length.
The user has to ensure the memory range is accessible while using the returned list.
If provided, finalizer will be run on the pointer once the typed list is GCed. If provided, token will be passed to finalizer, otherwise the this pointer itself will be passed.
import 'raya:ffi';
// A tiny allocator over the C library's malloc and free.
final class Libc implements Allocator {
static final _lib = DynamicLibrary.process();
static final _malloc = _lib.lookupFunction<Pointer<Void> Function(IntPtr), Pointer<Void> Function(int)>('malloc');
static final _free = _lib.lookupFunction<Void Function(Pointer<Void>), void Function(Pointer<Void>)>('free');
@override
Pointer<T> allocate<T extends NativeType>(int byteCount, {int? alignment}) => _malloc(byteCount).cast();
@override
void free(Pointer pointer) => _free(pointer.cast());
}
final libc = Libc();
void main() {
final p = libc<Int8>(4);
final view = p.asTypedList(4);
view.setAll(0, [10, -20, 30, -40]);
print('view: $view');
print('pointer [3]: ${p[3]}');
// The list and the pointer share the same native memory.
p[0] = 200;
print('after p[0] = 200: view[0] = ${view[0]}');
print('Int8List length ${view.length}, ${view.lengthInBytes} bytes');
libc.free(p);
}view: [10, -20, 30, -40] pointer [3]: -40 after p[0] = 200: view[0] = -56 Int8List length 4, 4 bytes
Operators
external int operator [](int index)The 8-bit two's complement integer at address + sizeOf<Int8> * index.
A Raya integer is truncated to 8 bits (as if by .toSigned(8)) before being stored, and the 8-bit value is sign-extended when it is loaded.
import 'raya:ffi';
// A tiny allocator over the C library's malloc and free.
final class Libc implements Allocator {
static final _lib = DynamicLibrary.process();
static final _malloc = _lib.lookupFunction<Pointer<Void> Function(IntPtr), Pointer<Void> Function(int)>('malloc');
static final _free = _lib.lookupFunction<Void Function(Pointer<Void>), void Function(Pointer<Void>)>('free');
@override
Pointer<T> allocate<T extends NativeType>(int byteCount, {int? alignment}) => _malloc(byteCount).cast();
@override
void free(Pointer pointer) => _free(pointer.cast());
}
final libc = Libc();
void main() {
final p = libc<Int8>(4);
const values = [10, -20, 30, -40];
for (var i = 0; i < 4; i++) {
p[i] = values[i];
}
print('p[0]: ${p[0]}, p[3]: ${p[3]}');
var sum = 0;
for (var i = 0; i < 4; i++) {
sum += p[i];
}
print('sum: $sum');
libc.free(p);
}p[0]: 10, p[3]: -40 sum: -20
external void operator []=(int index, int value)The 8-bit two's complement integer at address + sizeOf<Int8> * index.
A Raya integer is truncated to 8 bits (as if by .toSigned(8)) before being stored, and the 8-bit value is sign-extended when it is loaded.
import 'raya:ffi';
// A tiny allocator over the C library's malloc and free.
final class Libc implements Allocator {
static final _lib = DynamicLibrary.process();
static final _malloc = _lib.lookupFunction<Pointer<Void> Function(IntPtr), Pointer<Void> Function(int)>('malloc');
static final _free = _lib.lookupFunction<Void Function(Pointer<Void>), void Function(Pointer<Void>)>('free');
@override
Pointer<T> allocate<T extends NativeType>(int byteCount, {int? alignment}) => _malloc(byteCount).cast();
@override
void free(Pointer pointer) => _free(pointer.cast());
}
final libc = Libc();
void main() {
final p = libc<Int8>(3);
p[0] = -20;
p[1] = 30;
// Int8 holds -128..127, so 200 wraps.
p[2] = 200;
print('p[0] = ${p[0]}');
print('p[1] = ${p[1]}');
print('p[2] = ${p[2]} (stored 200)');
libc.free(p);
}p[0] = -20 p[1] = 30 p[2] = -56 (stored 200)
Pointer<Int8> operator +(int offset)A pointer to the offsetth Int8 after this one.
Returns a pointer to the Int8 whose address is offset times the size of Int8 after the address of this pointer. That is (this + offset).address == this.address + offset * sizeOf<Int8>.
Also (this + offset).value is equivalent to this[offset], and similarly for setting.
import 'raya:ffi';
// A tiny allocator over the C library's malloc and free.
final class Libc implements Allocator {
static final _lib = DynamicLibrary.process();
static final _malloc = _lib.lookupFunction<Pointer<Void> Function(IntPtr), Pointer<Void> Function(int)>('malloc');
static final _free = _lib.lookupFunction<Void Function(Pointer<Void>), void Function(Pointer<Void>)>('free');
@override
Pointer<T> allocate<T extends NativeType>(int byteCount, {int? alignment}) => _malloc(byteCount).cast();
@override
void free(Pointer pointer) => _free(pointer.cast());
}
final libc = Libc();
void main() {
final p = libc<Int8>(4);
for (var i = 0; i < 4; i++) {
p[i] = [10, -20, 30, -40][i];
}
final q = p + 3;
print('(p + 3).value: ${q.value}');
print('bytes between p, p+3: ${q.address - p.address}');
print('(p + 1)[1] == p[2]: ${(p + 1)[1] == p[2]}');
libc.free(p);
}(p + 3).value: -40 bytes between p, p+3: 3 (p + 1)[1] == p[2]: true
Pointer<Int8> operator -(int offset)A pointer to the offsetth Int8 before this one.
Equivalent to this + (-offset).
Returns a pointer to the Int8 whose address is offset times the size of Int8 before the address of this pointer. That is, (this - offset).address == this.address - offset * sizeOf<Int8>.
Also, (this - offset).value is equivalent to this[-offset], and similarly for setting,
import 'raya:ffi';
// A tiny allocator over the C library's malloc and free.
final class Libc implements Allocator {
static final _lib = DynamicLibrary.process();
static final _malloc = _lib.lookupFunction<Pointer<Void> Function(IntPtr), Pointer<Void> Function(int)>('malloc');
static final _free = _lib.lookupFunction<Void Function(Pointer<Void>), void Function(Pointer<Void>)>('free');
@override
Pointer<T> allocate<T extends NativeType>(int byteCount, {int? alignment}) => _malloc(byteCount).cast();
@override
void free(Pointer pointer) => _free(pointer.cast());
}
final libc = Libc();
void main() {
final p = libc<Int8>(4);
for (var i = 0; i < 4; i++) {
p[i] = [10, -20, 30, -40][i];
}
final end = p + 4; // one past the last element
print('(end - 1).value: ${(end - 1).value}');
print('end - 4 == p: ${end - 4 == p}');
print('bytes from end - 2: ${end.address - (end - 2).address}');
libc.free(p);
}(end - 1).value: -40 end - 4 == p: true bytes from end - 2: 2
Int16Pointer
extension Int16Pointer on Pointer<Int16>
Properties
external int get valueThe 16-bit two's complement integer at address.
A Raya integer is truncated to 16 bits (as if by .toSigned(16)) before being stored, and the 16-bit value is sign-extended when it is loaded.
The address must be 2-byte aligned.
external void set value(int value)import 'raya:ffi';
// A tiny allocator over the C library's malloc and free.
final class Libc implements Allocator {
static final _lib = DynamicLibrary.process();
static final _malloc = _lib.lookupFunction<Pointer<Void> Function(IntPtr), Pointer<Void> Function(int)>('malloc');
static final _free = _lib.lookupFunction<Void Function(Pointer<Void>), void Function(Pointer<Void>)>('free');
@override
Pointer<T> allocate<T extends NativeType>(int byteCount, {int? alignment}) => _malloc(byteCount).cast();
@override
void free(Pointer pointer) => _free(pointer.cast());
}
final libc = Libc();
void main() {
final p = libc<Int16>();
p.value = 1000;
print('stored 1000: ${p.value}');
// Int16 holds -32768..32767, so 40000 wraps.
p.value = 40000;
print('stored 40000: ${p.value}');
libc.free(p);
}stored 1000: 1000 stored 40000: -25536
Methods
Pointer<Int16> elementAt(int index)Pointer arithmetic (takes element size into account).
import 'raya:ffi';
// A tiny allocator over the C library's malloc and free.
final class Libc implements Allocator {
static final _lib = DynamicLibrary.process();
static final _malloc = _lib.lookupFunction<Pointer<Void> Function(IntPtr), Pointer<Void> Function(int)>('malloc');
static final _free = _lib.lookupFunction<Void Function(Pointer<Void>), void Function(Pointer<Void>)>('free');
@override
Pointer<T> allocate<T extends NativeType>(int byteCount, {int? alignment}) => _malloc(byteCount).cast();
@override
void free(Pointer pointer) => _free(pointer.cast());
}
final libc = Libc();
void main() {
final p = libc<Int16>(4);
const values = [1000, -2000, 3000, -4000];
for (var i = 0; i < 4; i++) {
p.elementAt(i).value = values[i];
}
print('element 2: ${p.elementAt(2).value}');
print('byte offset of 3: ${p.elementAt(3).address - p.address}');
print('sizeOf<Int16>(): ${sizeOf<Int16>()}');
libc.free(p);
}element 2: 3000 byte offset of 3: 6 sizeOf<Int16>(): 2
external Int16List asTypedList(int length, {@Since('3.1') Pointer<NativeFinalizerFunction>? finalizer, @Since('3.1') Pointer<Void>? token})Creates a typed list view backed by memory in the address space.
The returned view will allow access to the memory range from address to address + sizeOf<Int16> * length.
The user has to ensure the memory range is accessible while using the returned list.
If provided, finalizer will be run on the pointer once the typed list is GCed. If provided, token will be passed to finalizer, otherwise the this pointer itself will be passed.
The address must be 2-byte aligned.
import 'raya:ffi';
// A tiny allocator over the C library's malloc and free.
final class Libc implements Allocator {
static final _lib = DynamicLibrary.process();
static final _malloc = _lib.lookupFunction<Pointer<Void> Function(IntPtr), Pointer<Void> Function(int)>('malloc');
static final _free = _lib.lookupFunction<Void Function(Pointer<Void>), void Function(Pointer<Void>)>('free');
@override
Pointer<T> allocate<T extends NativeType>(int byteCount, {int? alignment}) => _malloc(byteCount).cast();
@override
void free(Pointer pointer) => _free(pointer.cast());
}
final libc = Libc();
void main() {
final p = libc<Int16>(4);
final view = p.asTypedList(4);
view.setAll(0, [1000, -2000, 3000, -4000]);
print('view: $view');
print('pointer [3]: ${p[3]}');
// The list and the pointer share the same native memory.
p[0] = 40000;
print('after p[0] = 40000: view[0] = ${view[0]}');
print('Int16List length ${view.length}, ${view.lengthInBytes} bytes');
libc.free(p);
}view: [1000, -2000, 3000, -4000] pointer [3]: -4000 after p[0] = 40000: view[0] = -25536 Int16List length 4, 8 bytes
Operators
external int operator [](int index)The 16-bit two's complement integer at address + sizeOf<Int16> * index.
A Raya integer is truncated to 16 bits (as if by .toSigned(16)) before being stored, and the 16-bit value is sign-extended when it is loaded.
The address must be 2-byte aligned.
import 'raya:ffi';
// A tiny allocator over the C library's malloc and free.
final class Libc implements Allocator {
static final _lib = DynamicLibrary.process();
static final _malloc = _lib.lookupFunction<Pointer<Void> Function(IntPtr), Pointer<Void> Function(int)>('malloc');
static final _free = _lib.lookupFunction<Void Function(Pointer<Void>), void Function(Pointer<Void>)>('free');
@override
Pointer<T> allocate<T extends NativeType>(int byteCount, {int? alignment}) => _malloc(byteCount).cast();
@override
void free(Pointer pointer) => _free(pointer.cast());
}
final libc = Libc();
void main() {
final p = libc<Int16>(4);
const values = [1000, -2000, 3000, -4000];
for (var i = 0; i < 4; i++) {
p[i] = values[i];
}
print('p[0]: ${p[0]}, p[3]: ${p[3]}');
var sum = 0;
for (var i = 0; i < 4; i++) {
sum += p[i];
}
print('sum: $sum');
libc.free(p);
}p[0]: 1000, p[3]: -4000 sum: -2000
external void operator []=(int index, int value)The 16-bit two's complement integer at address + sizeOf<Int16> * index.
A Raya integer is truncated to 16 bits (as if by .toSigned(16)) before being stored, and the 16-bit value is sign-extended when it is loaded.
The address must be 2-byte aligned.
import 'raya:ffi';
// A tiny allocator over the C library's malloc and free.
final class Libc implements Allocator {
static final _lib = DynamicLibrary.process();
static final _malloc = _lib.lookupFunction<Pointer<Void> Function(IntPtr), Pointer<Void> Function(int)>('malloc');
static final _free = _lib.lookupFunction<Void Function(Pointer<Void>), void Function(Pointer<Void>)>('free');
@override
Pointer<T> allocate<T extends NativeType>(int byteCount, {int? alignment}) => _malloc(byteCount).cast();
@override
void free(Pointer pointer) => _free(pointer.cast());
}
final libc = Libc();
void main() {
final p = libc<Int16>(3);
p[0] = -2000;
p[1] = 3000;
// Int16 holds -32768..32767, so 40000 wraps.
p[2] = 40000;
print('p[0] = ${p[0]}');
print('p[1] = ${p[1]}');
print('p[2] = ${p[2]} (stored 40000)');
libc.free(p);
}p[0] = -2000 p[1] = 3000 p[2] = -25536 (stored 40000)
Pointer<Int16> operator +(int offset)A pointer to the offsetth Int16 after this one.
Returns a pointer to the Int16 whose address is offset times the size of Int16 after the address of this pointer. That is (this + offset).address == this.address + offset * sizeOf<Int16>.
Also (this + offset).value is equivalent to this[offset], and similarly for setting.
import 'raya:ffi';
// A tiny allocator over the C library's malloc and free.
final class Libc implements Allocator {
static final _lib = DynamicLibrary.process();
static final _malloc = _lib.lookupFunction<Pointer<Void> Function(IntPtr), Pointer<Void> Function(int)>('malloc');
static final _free = _lib.lookupFunction<Void Function(Pointer<Void>), void Function(Pointer<Void>)>('free');
@override
Pointer<T> allocate<T extends NativeType>(int byteCount, {int? alignment}) => _malloc(byteCount).cast();
@override
void free(Pointer pointer) => _free(pointer.cast());
}
final libc = Libc();
void main() {
final p = libc<Int16>(4);
for (var i = 0; i < 4; i++) {
p[i] = [1000, -2000, 3000, -4000][i];
}
final q = p + 3;
print('(p + 3).value: ${q.value}');
print('bytes between p, p+3: ${q.address - p.address}');
print('(p + 1)[1] == p[2]: ${(p + 1)[1] == p[2]}');
libc.free(p);
}(p + 3).value: -4000 bytes between p, p+3: 6 (p + 1)[1] == p[2]: true
Pointer<Int16> operator -(int offset)A pointer to the offsetth Int16 before this one.
Equivalent to this + (-offset).
Returns a pointer to the Int16 whose address is offset times the size of Int16 before the address of this pointer. That is, (this - offset).address == this.address - offset * sizeOf<Int16>.
Also, (this - offset).value is equivalent to this[-offset], and similarly for setting,
import 'raya:ffi';
// A tiny allocator over the C library's malloc and free.
final class Libc implements Allocator {
static final _lib = DynamicLibrary.process();
static final _malloc = _lib.lookupFunction<Pointer<Void> Function(IntPtr), Pointer<Void> Function(int)>('malloc');
static final _free = _lib.lookupFunction<Void Function(Pointer<Void>), void Function(Pointer<Void>)>('free');
@override
Pointer<T> allocate<T extends NativeType>(int byteCount, {int? alignment}) => _malloc(byteCount).cast();
@override
void free(Pointer pointer) => _free(pointer.cast());
}
final libc = Libc();
void main() {
final p = libc<Int16>(4);
for (var i = 0; i < 4; i++) {
p[i] = [1000, -2000, 3000, -4000][i];
}
final end = p + 4; // one past the last element
print('(end - 1).value: ${(end - 1).value}');
print('end - 4 == p: ${end - 4 == p}');
print('bytes from end - 2: ${end.address - (end - 2).address}');
libc.free(p);
}(end - 1).value: -4000 end - 4 == p: true bytes from end - 2: 4
Int32Pointer
extension Int32Pointer on Pointer<Int32>
Properties
external int get valueThe 32-bit two's complement integer at address.
A Raya integer is truncated to 32 bits (as if by .toSigned(32)) before being stored, and the 32-bit value is sign-extended when it is loaded.
The address must be 4-byte aligned.
external void set value(int value)import 'raya:ffi';
// A tiny allocator over the C library's malloc and free.
final class Libc implements Allocator {
static final _lib = DynamicLibrary.process();
static final _malloc = _lib.lookupFunction<Pointer<Void> Function(IntPtr), Pointer<Void> Function(int)>('malloc');
static final _free = _lib.lookupFunction<Void Function(Pointer<Void>), void Function(Pointer<Void>)>('free');
@override
Pointer<T> allocate<T extends NativeType>(int byteCount, {int? alignment}) => _malloc(byteCount).cast();
@override
void free(Pointer pointer) => _free(pointer.cast());
}
final libc = Libc();
void main() {
final p = libc<Int32>();
p.value = 100000;
print('stored 100000: ${p.value}');
// Int32 holds about +-2.1e9, so 3e9 wraps.
p.value = 3000000000;
print('stored 3000000000: ${p.value}');
libc.free(p);
}stored 100000: 100000 stored 3000000000: -1294967296
Methods
Pointer<Int32> elementAt(int index)Pointer arithmetic (takes element size into account).
import 'raya:ffi';
// A tiny allocator over the C library's malloc and free.
final class Libc implements Allocator {
static final _lib = DynamicLibrary.process();
static final _malloc = _lib.lookupFunction<Pointer<Void> Function(IntPtr), Pointer<Void> Function(int)>('malloc');
static final _free = _lib.lookupFunction<Void Function(Pointer<Void>), void Function(Pointer<Void>)>('free');
@override
Pointer<T> allocate<T extends NativeType>(int byteCount, {int? alignment}) => _malloc(byteCount).cast();
@override
void free(Pointer pointer) => _free(pointer.cast());
}
final libc = Libc();
void main() {
final p = libc<Int32>(4);
const values = [100000, -200000, 300000, -400000];
for (var i = 0; i < 4; i++) {
p.elementAt(i).value = values[i];
}
print('element 2: ${p.elementAt(2).value}');
print('byte offset of 3: ${p.elementAt(3).address - p.address}');
print('sizeOf<Int32>(): ${sizeOf<Int32>()}');
libc.free(p);
}element 2: 300000 byte offset of 3: 12 sizeOf<Int32>(): 4
external Int32List asTypedList(int length, {@Since('3.1') Pointer<NativeFinalizerFunction>? finalizer, @Since('3.1') Pointer<Void>? token})Creates a typed list view backed by memory in the address space.
The returned view will allow access to the memory range from address to address + sizeOf<Int32> * length.
The user has to ensure the memory range is accessible while using the returned list.
If provided, finalizer will be run on the pointer once the typed list is GCed. If provided, token will be passed to finalizer, otherwise the this pointer itself will be passed.
The address must be 4-byte aligned.
import 'raya:ffi';
// A tiny allocator over the C library's malloc and free.
final class Libc implements Allocator {
static final _lib = DynamicLibrary.process();
static final _malloc = _lib.lookupFunction<Pointer<Void> Function(IntPtr), Pointer<Void> Function(int)>('malloc');
static final _free = _lib.lookupFunction<Void Function(Pointer<Void>), void Function(Pointer<Void>)>('free');
@override
Pointer<T> allocate<T extends NativeType>(int byteCount, {int? alignment}) => _malloc(byteCount).cast();
@override
void free(Pointer pointer) => _free(pointer.cast());
}
final libc = Libc();
void main() {
final p = libc<Int32>(4);
final view = p.asTypedList(4);
view.setAll(0, [100000, -200000, 300000, -400000]);
print('view: $view');
print('pointer [3]: ${p[3]}');
// The list and the pointer share the same native memory.
p[0] = 3000000000;
print('after p[0] = 3000000000: view[0] = ${view[0]}');
print('Int32List length ${view.length}, ${view.lengthInBytes} bytes');
libc.free(p);
}view: [100000, -200000, 300000, -400000] pointer [3]: -400000 after p[0] = 3000000000: view[0] = -1294967296 Int32List length 4, 16 bytes
Operators
external int operator [](int index)The 32-bit two's complement integer at address + sizeOf<Int32> * index.
A Raya integer is truncated to 32 bits (as if by .toSigned(32)) before being stored, and the 32-bit value is sign-extended when it is loaded.
The address must be 4-byte aligned.
import 'raya:ffi';
// A tiny allocator over the C library's malloc and free.
final class Libc implements Allocator {
static final _lib = DynamicLibrary.process();
static final _malloc = _lib.lookupFunction<Pointer<Void> Function(IntPtr), Pointer<Void> Function(int)>('malloc');
static final _free = _lib.lookupFunction<Void Function(Pointer<Void>), void Function(Pointer<Void>)>('free');
@override
Pointer<T> allocate<T extends NativeType>(int byteCount, {int? alignment}) => _malloc(byteCount).cast();
@override
void free(Pointer pointer) => _free(pointer.cast());
}
final libc = Libc();
void main() {
final p = libc<Int32>(4);
const values = [100000, -200000, 300000, -400000];
for (var i = 0; i < 4; i++) {
p[i] = values[i];
}
print('p[0]: ${p[0]}, p[3]: ${p[3]}');
var sum = 0;
for (var i = 0; i < 4; i++) {
sum += p[i];
}
print('sum: $sum');
libc.free(p);
}p[0]: 100000, p[3]: -400000 sum: -200000
external void operator []=(int index, int value)The 32-bit two's complement integer at address + sizeOf<Int32> * index.
A Raya integer is truncated to 32 bits (as if by .toSigned(32)) before being stored, and the 32-bit value is sign-extended when it is loaded.
The address must be 4-byte aligned.
import 'raya:ffi';
// A tiny allocator over the C library's malloc and free.
final class Libc implements Allocator {
static final _lib = DynamicLibrary.process();
static final _malloc = _lib.lookupFunction<Pointer<Void> Function(IntPtr), Pointer<Void> Function(int)>('malloc');
static final _free = _lib.lookupFunction<Void Function(Pointer<Void>), void Function(Pointer<Void>)>('free');
@override
Pointer<T> allocate<T extends NativeType>(int byteCount, {int? alignment}) => _malloc(byteCount).cast();
@override
void free(Pointer pointer) => _free(pointer.cast());
}
final libc = Libc();
void main() {
final p = libc<Int32>(3);
p[0] = -200000;
p[1] = 300000;
// Int32 holds about +-2.1e9, so 3e9 wraps.
p[2] = 3000000000;
print('p[0] = ${p[0]}');
print('p[1] = ${p[1]}');
print('p[2] = ${p[2]} (stored 3000000000)');
libc.free(p);
}p[0] = -200000 p[1] = 300000 p[2] = -1294967296 (stored 3000000000)
Pointer<Int32> operator +(int offset)A pointer to the offsetth Int32 after this one.
Returns a pointer to the Int32 whose address is offset times the size of Int32 after the address of this pointer. That is (this + offset).address == this.address + offset * sizeOf<Int32>.
Also (this + offset).value is equivalent to this[offset], and similarly for setting.
import 'raya:ffi';
// A tiny allocator over the C library's malloc and free.
final class Libc implements Allocator {
static final _lib = DynamicLibrary.process();
static final _malloc = _lib.lookupFunction<Pointer<Void> Function(IntPtr), Pointer<Void> Function(int)>('malloc');
static final _free = _lib.lookupFunction<Void Function(Pointer<Void>), void Function(Pointer<Void>)>('free');
@override
Pointer<T> allocate<T extends NativeType>(int byteCount, {int? alignment}) => _malloc(byteCount).cast();
@override
void free(Pointer pointer) => _free(pointer.cast());
}
final libc = Libc();
void main() {
final p = libc<Int32>(4);
for (var i = 0; i < 4; i++) {
p[i] = [100000, -200000, 300000, -400000][i];
}
final q = p + 3;
print('(p + 3).value: ${q.value}');
print('bytes between p, p+3: ${q.address - p.address}');
print('(p + 1)[1] == p[2]: ${(p + 1)[1] == p[2]}');
libc.free(p);
}(p + 3).value: -400000 bytes between p, p+3: 12 (p + 1)[1] == p[2]: true
Pointer<Int32> operator -(int offset)A pointer to the offsetth Int32 before this one.
Equivalent to this + (-offset).
Returns a pointer to the Int32 whose address is offset times the size of Int32 before the address of this pointer. That is, (this - offset).address == this.address - offset * sizeOf<Int32>.
Also, (this - offset).value is equivalent to this[-offset], and similarly for setting,
import 'raya:ffi';
// A tiny allocator over the C library's malloc and free.
final class Libc implements Allocator {
static final _lib = DynamicLibrary.process();
static final _malloc = _lib.lookupFunction<Pointer<Void> Function(IntPtr), Pointer<Void> Function(int)>('malloc');
static final _free = _lib.lookupFunction<Void Function(Pointer<Void>), void Function(Pointer<Void>)>('free');
@override
Pointer<T> allocate<T extends NativeType>(int byteCount, {int? alignment}) => _malloc(byteCount).cast();
@override
void free(Pointer pointer) => _free(pointer.cast());
}
final libc = Libc();
void main() {
final p = libc<Int32>(4);
for (var i = 0; i < 4; i++) {
p[i] = [100000, -200000, 300000, -400000][i];
}
final end = p + 4; // one past the last element
print('(end - 1).value: ${(end - 1).value}');
print('end - 4 == p: ${end - 4 == p}');
print('bytes from end - 2: ${end.address - (end - 2).address}');
libc.free(p);
}(end - 1).value: -400000 end - 4 == p: true bytes from end - 2: 8
Int64Pointer
extension Int64Pointer on Pointer<Int64>
Properties
external int get valueThe 64-bit two's complement integer at address.
The address must be 8-byte aligned.
external void set value(int value)import 'raya:ffi';
// A tiny allocator over the C library's malloc and free.
final class Libc implements Allocator {
static final _lib = DynamicLibrary.process();
static final _malloc = _lib.lookupFunction<Pointer<Void> Function(IntPtr), Pointer<Void> Function(int)>('malloc');
static final _free = _lib.lookupFunction<Void Function(Pointer<Void>), void Function(Pointer<Void>)>('free');
@override
Pointer<T> allocate<T extends NativeType>(int byteCount, {int? alignment}) => _malloc(byteCount).cast();
@override
void free(Pointer pointer) => _free(pointer.cast());
}
final libc = Libc();
void main() {
final p = libc<Int64>();
p.value = 1099511627776;
print('stored 1099511627776: ${p.value}');
// Int64 is the full int range: the minimum survives.
p.value = -9223372036854775808;
print('stored -9223372036854775808: ${p.value}');
libc.free(p);
}stored 1099511627776: 1099511627776 stored -9223372036854775808: -9223372036854775808
Methods
Pointer<Int64> elementAt(int index)Pointer arithmetic (takes element size into account).
import 'raya:ffi';
// A tiny allocator over the C library's malloc and free.
final class Libc implements Allocator {
static final _lib = DynamicLibrary.process();
static final _malloc = _lib.lookupFunction<Pointer<Void> Function(IntPtr), Pointer<Void> Function(int)>('malloc');
static final _free = _lib.lookupFunction<Void Function(Pointer<Void>), void Function(Pointer<Void>)>('free');
@override
Pointer<T> allocate<T extends NativeType>(int byteCount, {int? alignment}) => _malloc(byteCount).cast();
@override
void free(Pointer pointer) => _free(pointer.cast());
}
final libc = Libc();
void main() {
final p = libc<Int64>(4);
const values = [1099511627776, -1099511627776, 7, -7];
for (var i = 0; i < 4; i++) {
p.elementAt(i).value = values[i];
}
print('element 2: ${p.elementAt(2).value}');
print('byte offset of 3: ${p.elementAt(3).address - p.address}');
print('sizeOf<Int64>(): ${sizeOf<Int64>()}');
libc.free(p);
}element 2: 7 byte offset of 3: 24 sizeOf<Int64>(): 8
external Int64List asTypedList(int length, {@Since('3.1') Pointer<NativeFinalizerFunction>? finalizer, @Since('3.1') Pointer<Void>? token})Creates a typed list view backed by memory in the address space.
The returned view will allow access to the memory range from address to address + sizeOf<Int64> * length.
The user has to ensure the memory range is accessible while using the returned list.
If provided, finalizer will be run on the pointer once the typed list is GCed. If provided, token will be passed to finalizer, otherwise the this pointer itself will be passed.
The address must be 8-byte aligned.
import 'raya:ffi';
// A tiny allocator over the C library's malloc and free.
final class Libc implements Allocator {
static final _lib = DynamicLibrary.process();
static final _malloc = _lib.lookupFunction<Pointer<Void> Function(IntPtr), Pointer<Void> Function(int)>('malloc');
static final _free = _lib.lookupFunction<Void Function(Pointer<Void>), void Function(Pointer<Void>)>('free');
@override
Pointer<T> allocate<T extends NativeType>(int byteCount, {int? alignment}) => _malloc(byteCount).cast();
@override
void free(Pointer pointer) => _free(pointer.cast());
}
final libc = Libc();
void main() {
final p = libc<Int64>(4);
final view = p.asTypedList(4);
view.setAll(0, [1099511627776, -1099511627776, 7, -7]);
print('view: $view');
print('pointer [3]: ${p[3]}');
// The list and the pointer share the same native memory.
p[0] = -9223372036854775808;
print('after p[0] = -9223372036854775808: view[0] = ${view[0]}');
print('Int64List length ${view.length}, ${view.lengthInBytes} bytes');
libc.free(p);
}view: [1099511627776, -1099511627776, 7, -7] pointer [3]: -7 after p[0] = -9223372036854775808: view[0] = -9223372036854775808 Int64List length 4, 32 bytes
Operators
external int operator [](int index)The 64-bit two's complement integer at address + sizeOf<Int64> * index.
The address must be 8-byte aligned.
import 'raya:ffi';
// A tiny allocator over the C library's malloc and free.
final class Libc implements Allocator {
static final _lib = DynamicLibrary.process();
static final _malloc = _lib.lookupFunction<Pointer<Void> Function(IntPtr), Pointer<Void> Function(int)>('malloc');
static final _free = _lib.lookupFunction<Void Function(Pointer<Void>), void Function(Pointer<Void>)>('free');
@override
Pointer<T> allocate<T extends NativeType>(int byteCount, {int? alignment}) => _malloc(byteCount).cast();
@override
void free(Pointer pointer) => _free(pointer.cast());
}
final libc = Libc();
void main() {
final p = libc<Int64>(4);
const values = [1099511627776, -1099511627776, 7, -7];
for (var i = 0; i < 4; i++) {
p[i] = values[i];
}
print('p[0]: ${p[0]}, p[3]: ${p[3]}');
var sum = 0;
for (var i = 0; i < 4; i++) {
sum += p[i];
}
print('sum: $sum');
libc.free(p);
}p[0]: 1099511627776, p[3]: -7 sum: 0
external void operator []=(int index, int value)The 64-bit two's complement integer at address + sizeOf<Int64> * index.
The address must be 8-byte aligned.
import 'raya:ffi';
// A tiny allocator over the C library's malloc and free.
final class Libc implements Allocator {
static final _lib = DynamicLibrary.process();
static final _malloc = _lib.lookupFunction<Pointer<Void> Function(IntPtr), Pointer<Void> Function(int)>('malloc');
static final _free = _lib.lookupFunction<Void Function(Pointer<Void>), void Function(Pointer<Void>)>('free');
@override
Pointer<T> allocate<T extends NativeType>(int byteCount, {int? alignment}) => _malloc(byteCount).cast();
@override
void free(Pointer pointer) => _free(pointer.cast());
}
final libc = Libc();
void main() {
final p = libc<Int64>(3);
p[0] = -1099511627776;
p[1] = 7;
// Int64 is the full int range: the minimum survives.
p[2] = -9223372036854775808;
print('p[0] = ${p[0]}');
print('p[1] = ${p[1]}');
print('p[2] = ${p[2]} (stored -9223372036854775808)');
libc.free(p);
}p[0] = -1099511627776 p[1] = 7 p[2] = -9223372036854775808 (stored -9223372036854775808)
Pointer<Int64> operator +(int offset)A pointer to the offsetth Int64 after this one.
Returns a pointer to the Int64 whose address is offset times the size of Int64 after the address of this pointer. That is (this + offset).address == this.address + offset * sizeOf<Int64>.
Also (this + offset).value is equivalent to this[offset], and similarly for setting.
import 'raya:ffi';
// A tiny allocator over the C library's malloc and free.
final class Libc implements Allocator {
static final _lib = DynamicLibrary.process();
static final _malloc = _lib.lookupFunction<Pointer<Void> Function(IntPtr), Pointer<Void> Function(int)>('malloc');
static final _free = _lib.lookupFunction<Void Function(Pointer<Void>), void Function(Pointer<Void>)>('free');
@override
Pointer<T> allocate<T extends NativeType>(int byteCount, {int? alignment}) => _malloc(byteCount).cast();
@override
void free(Pointer pointer) => _free(pointer.cast());
}
final libc = Libc();
void main() {
final p = libc<Int64>(4);
for (var i = 0; i < 4; i++) {
p[i] = [1099511627776, -1099511627776, 7, -7][i];
}
final q = p + 3;
print('(p + 3).value: ${q.value}');
print('bytes between p, p+3: ${q.address - p.address}');
print('(p + 1)[1] == p[2]: ${(p + 1)[1] == p[2]}');
libc.free(p);
}(p + 3).value: -7 bytes between p, p+3: 24 (p + 1)[1] == p[2]: true
Pointer<Int64> operator -(int offset)A pointer to the offsetth Int64 before this one.
Equivalent to this + (-offset).
Returns a pointer to the Int64 whose address is offset times the size of Int64 before the address of this pointer. That is, (this - offset).address == this.address - offset * sizeOf<Int64>.
Also, (this - offset).value is equivalent to this[-offset], and similarly for setting,
import 'raya:ffi';
// A tiny allocator over the C library's malloc and free.
final class Libc implements Allocator {
static final _lib = DynamicLibrary.process();
static final _malloc = _lib.lookupFunction<Pointer<Void> Function(IntPtr), Pointer<Void> Function(int)>('malloc');
static final _free = _lib.lookupFunction<Void Function(Pointer<Void>), void Function(Pointer<Void>)>('free');
@override
Pointer<T> allocate<T extends NativeType>(int byteCount, {int? alignment}) => _malloc(byteCount).cast();
@override
void free(Pointer pointer) => _free(pointer.cast());
}
final libc = Libc();
void main() {
final p = libc<Int64>(4);
for (var i = 0; i < 4; i++) {
p[i] = [1099511627776, -1099511627776, 7, -7][i];
}
final end = p + 4; // one past the last element
print('(end - 1).value: ${(end - 1).value}');
print('end - 4 == p: ${end - 4 == p}');
print('bytes from end - 2: ${end.address - (end - 2).address}');
libc.free(p);
}(end - 1).value: -7 end - 4 == p: true bytes from end - 2: 16
Uint8Pointer
extension Uint8Pointer on Pointer<Uint8>
Properties
external int get valueThe 8-bit unsigned integer at address.
A Raya integer is truncated to 8 bits (as if by .toUnsigned(8)) before being stored, and the 8-bit value is zero-extended when it is loaded.
external void set value(int value)import 'raya:ffi';
// A tiny allocator over the C library's malloc and free.
final class Libc implements Allocator {
static final _lib = DynamicLibrary.process();
static final _malloc = _lib.lookupFunction<Pointer<Void> Function(IntPtr), Pointer<Void> Function(int)>('malloc');
static final _free = _lib.lookupFunction<Void Function(Pointer<Void>), void Function(Pointer<Void>)>('free');
@override
Pointer<T> allocate<T extends NativeType>(int byteCount, {int? alignment}) => _malloc(byteCount).cast();
@override
void free(Pointer pointer) => _free(pointer.cast());
}
final libc = Libc();
void main() {
final p = libc<Uint8>();
p.value = 10;
print('stored 10: ${p.value}');
// Uint8 holds 0..255, so 300 wraps.
p.value = 300;
print('stored 300: ${p.value}');
libc.free(p);
}stored 10: 10 stored 300: 44
Methods
Pointer<Uint8> elementAt(int index)Pointer arithmetic (takes element size into account).
import 'raya:ffi';
// A tiny allocator over the C library's malloc and free.
final class Libc implements Allocator {
static final _lib = DynamicLibrary.process();
static final _malloc = _lib.lookupFunction<Pointer<Void> Function(IntPtr), Pointer<Void> Function(int)>('malloc');
static final _free = _lib.lookupFunction<Void Function(Pointer<Void>), void Function(Pointer<Void>)>('free');
@override
Pointer<T> allocate<T extends NativeType>(int byteCount, {int? alignment}) => _malloc(byteCount).cast();
@override
void free(Pointer pointer) => _free(pointer.cast());
}
final libc = Libc();
void main() {
final p = libc<Uint8>(4);
const values = [10, 20, 250, 255];
for (var i = 0; i < 4; i++) {
p.elementAt(i).value = values[i];
}
print('element 2: ${p.elementAt(2).value}');
print('byte offset of 3: ${p.elementAt(3).address - p.address}');
print('sizeOf<Uint8>(): ${sizeOf<Uint8>()}');
libc.free(p);
}element 2: 250 byte offset of 3: 3 sizeOf<Uint8>(): 1
external Uint8List asTypedList(int length, {@Since('3.1') Pointer<NativeFinalizerFunction>? finalizer, @Since('3.1') Pointer<Void>? token})Creates a typed list view backed by memory in the address space.
The returned view will allow access to the memory range from address to address + sizeOf<Uint8> * length.
The user has to ensure the memory range is accessible while using the returned list.
If provided, finalizer will be run on the pointer once the typed list is GCed. If provided, token will be passed to finalizer, otherwise the this pointer itself will be passed.
import 'raya:ffi';
// A tiny allocator over the C library's malloc and free.
final class Libc implements Allocator {
static final _lib = DynamicLibrary.process();
static final _malloc = _lib.lookupFunction<Pointer<Void> Function(IntPtr), Pointer<Void> Function(int)>('malloc');
static final _free = _lib.lookupFunction<Void Function(Pointer<Void>), void Function(Pointer<Void>)>('free');
@override
Pointer<T> allocate<T extends NativeType>(int byteCount, {int? alignment}) => _malloc(byteCount).cast();
@override
void free(Pointer pointer) => _free(pointer.cast());
}
final libc = Libc();
void main() {
final p = libc<Uint8>(4);
final view = p.asTypedList(4);
view.setAll(0, [10, 20, 250, 255]);
print('view: $view');
print('pointer [3]: ${p[3]}');
// The list and the pointer share the same native memory.
p[0] = 300;
print('after p[0] = 300: view[0] = ${view[0]}');
print('Uint8List length ${view.length}, ${view.lengthInBytes} bytes');
libc.free(p);
}view: [10, 20, 250, 255] pointer [3]: 255 after p[0] = 300: view[0] = 44 Uint8List length 4, 4 bytes
Operators
external int operator [](int index)The 8-bit unsigned integer at address + sizeOf<Uint8> * index.
A Raya integer is truncated to 8 bits (as if by .toUnsigned(8)) before being stored, and the 8-bit value is zero-extended when it is loaded.
import 'raya:ffi';
// A tiny allocator over the C library's malloc and free.
final class Libc implements Allocator {
static final _lib = DynamicLibrary.process();
static final _malloc = _lib.lookupFunction<Pointer<Void> Function(IntPtr), Pointer<Void> Function(int)>('malloc');
static final _free = _lib.lookupFunction<Void Function(Pointer<Void>), void Function(Pointer<Void>)>('free');
@override
Pointer<T> allocate<T extends NativeType>(int byteCount, {int? alignment}) => _malloc(byteCount).cast();
@override
void free(Pointer pointer) => _free(pointer.cast());
}
final libc = Libc();
void main() {
final p = libc<Uint8>(4);
const values = [10, 20, 250, 255];
for (var i = 0; i < 4; i++) {
p[i] = values[i];
}
print('p[0]: ${p[0]}, p[3]: ${p[3]}');
var sum = 0;
for (var i = 0; i < 4; i++) {
sum += p[i];
}
print('sum: $sum');
libc.free(p);
}p[0]: 10, p[3]: 255 sum: 535
external void operator []=(int index, int value)The 8-bit unsigned integer at address + sizeOf<Uint8> * index.
A Raya integer is truncated to 8 bits (as if by .toUnsigned(8)) before being stored, and the 8-bit value is zero-extended when it is loaded.
import 'raya:ffi';
// A tiny allocator over the C library's malloc and free.
final class Libc implements Allocator {
static final _lib = DynamicLibrary.process();
static final _malloc = _lib.lookupFunction<Pointer<Void> Function(IntPtr), Pointer<Void> Function(int)>('malloc');
static final _free = _lib.lookupFunction<Void Function(Pointer<Void>), void Function(Pointer<Void>)>('free');
@override
Pointer<T> allocate<T extends NativeType>(int byteCount, {int? alignment}) => _malloc(byteCount).cast();
@override
void free(Pointer pointer) => _free(pointer.cast());
}
final libc = Libc();
void main() {
final p = libc<Uint8>(3);
p[0] = 20;
p[1] = 250;
// Uint8 holds 0..255, so 300 wraps.
p[2] = 300;
print('p[0] = ${p[0]}');
print('p[1] = ${p[1]}');
print('p[2] = ${p[2]} (stored 300)');
libc.free(p);
}p[0] = 20 p[1] = 250 p[2] = 44 (stored 300)
Pointer<Uint8> operator +(int offset)A pointer to the offsetth Uint8 after this one.
Returns a pointer to the Uint8 whose address is offset times the size of Uint8 after the address of this pointer. That is (this + offset).address == this.address + offset * sizeOf<Uint8>.
Also (this + offset).value is equivalent to this[offset], and similarly for setting.
import 'raya:ffi';
// A tiny allocator over the C library's malloc and free.
final class Libc implements Allocator {
static final _lib = DynamicLibrary.process();
static final _malloc = _lib.lookupFunction<Pointer<Void> Function(IntPtr), Pointer<Void> Function(int)>('malloc');
static final _free = _lib.lookupFunction<Void Function(Pointer<Void>), void Function(Pointer<Void>)>('free');
@override
Pointer<T> allocate<T extends NativeType>(int byteCount, {int? alignment}) => _malloc(byteCount).cast();
@override
void free(Pointer pointer) => _free(pointer.cast());
}
final libc = Libc();
void main() {
final p = libc<Uint8>(4);
for (var i = 0; i < 4; i++) {
p[i] = [10, 20, 250, 255][i];
}
final q = p + 3;
print('(p + 3).value: ${q.value}');
print('bytes between p, p+3: ${q.address - p.address}');
print('(p + 1)[1] == p[2]: ${(p + 1)[1] == p[2]}');
libc.free(p);
}(p + 3).value: 255 bytes between p, p+3: 3 (p + 1)[1] == p[2]: true
Pointer<Uint8> operator -(int offset)A pointer to the offsetth Uint8 before this one.
Equivalent to this + (-offset).
Returns a pointer to the Uint8 whose address is offset times the size of Uint8 before the address of this pointer. That is, (this - offset).address == this.address - offset * sizeOf<Uint8>.
Also, (this - offset).value is equivalent to this[-offset], and similarly for setting,
import 'raya:ffi';
// A tiny allocator over the C library's malloc and free.
final class Libc implements Allocator {
static final _lib = DynamicLibrary.process();
static final _malloc = _lib.lookupFunction<Pointer<Void> Function(IntPtr), Pointer<Void> Function(int)>('malloc');
static final _free = _lib.lookupFunction<Void Function(Pointer<Void>), void Function(Pointer<Void>)>('free');
@override
Pointer<T> allocate<T extends NativeType>(int byteCount, {int? alignment}) => _malloc(byteCount).cast();
@override
void free(Pointer pointer) => _free(pointer.cast());
}
final libc = Libc();
void main() {
final p = libc<Uint8>(4);
for (var i = 0; i < 4; i++) {
p[i] = [10, 20, 250, 255][i];
}
final end = p + 4; // one past the last element
print('(end - 1).value: ${(end - 1).value}');
print('end - 4 == p: ${end - 4 == p}');
print('bytes from end - 2: ${end.address - (end - 2).address}');
libc.free(p);
}(end - 1).value: 255 end - 4 == p: true bytes from end - 2: 2
Uint16Pointer
extension Uint16Pointer on Pointer<Uint16>
Properties
external int get valueThe 16-bit unsigned integer at address.
A Raya integer is truncated to 16 bits (as if by .toUnsigned(16)) before being stored, and the 16-bit value is zero-extended when it is loaded.
The address must be 2-byte aligned.
external void set value(int value)import 'raya:ffi';
// A tiny allocator over the C library's malloc and free.
final class Libc implements Allocator {
static final _lib = DynamicLibrary.process();
static final _malloc = _lib.lookupFunction<Pointer<Void> Function(IntPtr), Pointer<Void> Function(int)>('malloc');
static final _free = _lib.lookupFunction<Void Function(Pointer<Void>), void Function(Pointer<Void>)>('free');
@override
Pointer<T> allocate<T extends NativeType>(int byteCount, {int? alignment}) => _malloc(byteCount).cast();
@override
void free(Pointer pointer) => _free(pointer.cast());
}
final libc = Libc();
void main() {
final p = libc<Uint16>();
p.value = 1000;
print('stored 1000: ${p.value}');
// Uint16 holds 0..65535, so 70000 wraps.
p.value = 70000;
print('stored 70000: ${p.value}');
libc.free(p);
}stored 1000: 1000 stored 70000: 4464
Methods
Pointer<Uint16> elementAt(int index)Pointer arithmetic (takes element size into account).
import 'raya:ffi';
// A tiny allocator over the C library's malloc and free.
final class Libc implements Allocator {
static final _lib = DynamicLibrary.process();
static final _malloc = _lib.lookupFunction<Pointer<Void> Function(IntPtr), Pointer<Void> Function(int)>('malloc');
static final _free = _lib.lookupFunction<Void Function(Pointer<Void>), void Function(Pointer<Void>)>('free');
@override
Pointer<T> allocate<T extends NativeType>(int byteCount, {int? alignment}) => _malloc(byteCount).cast();
@override
void free(Pointer pointer) => _free(pointer.cast());
}
final libc = Libc();
void main() {
final p = libc<Uint16>(4);
const values = [1000, 2000, 65000, 65535];
for (var i = 0; i < 4; i++) {
p.elementAt(i).value = values[i];
}
print('element 2: ${p.elementAt(2).value}');
print('byte offset of 3: ${p.elementAt(3).address - p.address}');
print('sizeOf<Uint16>(): ${sizeOf<Uint16>()}');
libc.free(p);
}element 2: 65000 byte offset of 3: 6 sizeOf<Uint16>(): 2
external Uint16List asTypedList(int length, {@Since('3.1') Pointer<NativeFinalizerFunction>? finalizer, @Since('3.1') Pointer<Void>? token})Creates a typed list view backed by memory in the address space.
The returned view will allow access to the memory range from address to address + sizeOf<Uint16> * length.
The user has to ensure the memory range is accessible while using the returned list.
If provided, finalizer will be run on the pointer once the typed list is GCed. If provided, token will be passed to finalizer, otherwise the this pointer itself will be passed.
The address must be 2-byte aligned.
import 'raya:ffi';
// A tiny allocator over the C library's malloc and free.
final class Libc implements Allocator {
static final _lib = DynamicLibrary.process();
static final _malloc = _lib.lookupFunction<Pointer<Void> Function(IntPtr), Pointer<Void> Function(int)>('malloc');
static final _free = _lib.lookupFunction<Void Function(Pointer<Void>), void Function(Pointer<Void>)>('free');
@override
Pointer<T> allocate<T extends NativeType>(int byteCount, {int? alignment}) => _malloc(byteCount).cast();
@override
void free(Pointer pointer) => _free(pointer.cast());
}
final libc = Libc();
void main() {
final p = libc<Uint16>(4);
final view = p.asTypedList(4);
view.setAll(0, [1000, 2000, 65000, 65535]);
print('view: $view');
print('pointer [3]: ${p[3]}');
// The list and the pointer share the same native memory.
p[0] = 70000;
print('after p[0] = 70000: view[0] = ${view[0]}');
print('Uint16List length ${view.length}, ${view.lengthInBytes} bytes');
libc.free(p);
}view: [1000, 2000, 65000, 65535] pointer [3]: 65535 after p[0] = 70000: view[0] = 4464 Uint16List length 4, 8 bytes
Operators
external int operator [](int index)The 16-bit unsigned integer at address + sizeOf<Uint16> * index.
A Raya integer is truncated to 16 bits (as if by .toUnsigned(16)) before being stored, and the 16-bit value is zero-extended when it is loaded.
The address must be 2-byte aligned.
import 'raya:ffi';
// A tiny allocator over the C library's malloc and free.
final class Libc implements Allocator {
static final _lib = DynamicLibrary.process();
static final _malloc = _lib.lookupFunction<Pointer<Void> Function(IntPtr), Pointer<Void> Function(int)>('malloc');
static final _free = _lib.lookupFunction<Void Function(Pointer<Void>), void Function(Pointer<Void>)>('free');
@override
Pointer<T> allocate<T extends NativeType>(int byteCount, {int? alignment}) => _malloc(byteCount).cast();
@override
void free(Pointer pointer) => _free(pointer.cast());
}
final libc = Libc();
void main() {
final p = libc<Uint16>(4);
const values = [1000, 2000, 65000, 65535];
for (var i = 0; i < 4; i++) {
p[i] = values[i];
}
print('p[0]: ${p[0]}, p[3]: ${p[3]}');
var sum = 0;
for (var i = 0; i < 4; i++) {
sum += p[i];
}
print('sum: $sum');
libc.free(p);
}p[0]: 1000, p[3]: 65535 sum: 133535
external void operator []=(int index, int value)The 16-bit unsigned integer at address + sizeOf<Uint16> * index.
A Raya integer is truncated to 16 bits (as if by .toUnsigned(16)) before being stored, and the 16-bit value is zero-extended when it is loaded.
The address must be 2-byte aligned.
import 'raya:ffi';
// A tiny allocator over the C library's malloc and free.
final class Libc implements Allocator {
static final _lib = DynamicLibrary.process();
static final _malloc = _lib.lookupFunction<Pointer<Void> Function(IntPtr), Pointer<Void> Function(int)>('malloc');
static final _free = _lib.lookupFunction<Void Function(Pointer<Void>), void Function(Pointer<Void>)>('free');
@override
Pointer<T> allocate<T extends NativeType>(int byteCount, {int? alignment}) => _malloc(byteCount).cast();
@override
void free(Pointer pointer) => _free(pointer.cast());
}
final libc = Libc();
void main() {
final p = libc<Uint16>(3);
p[0] = 2000;
p[1] = 65000;
// Uint16 holds 0..65535, so 70000 wraps.
p[2] = 70000;
print('p[0] = ${p[0]}');
print('p[1] = ${p[1]}');
print('p[2] = ${p[2]} (stored 70000)');
libc.free(p);
}p[0] = 2000 p[1] = 65000 p[2] = 4464 (stored 70000)
Pointer<Uint16> operator +(int offset)A pointer to the offsetth Uint16 after this one.
Returns a pointer to the Uint16 whose address is offset times the size of Uint16 after the address of this pointer. That is (this + offset).address == this.address + offset * sizeOf<Uint16>.
Also (this + offset).value is equivalent to this[offset], and similarly for setting.
import 'raya:ffi';
// A tiny allocator over the C library's malloc and free.
final class Libc implements Allocator {
static final _lib = DynamicLibrary.process();
static final _malloc = _lib.lookupFunction<Pointer<Void> Function(IntPtr), Pointer<Void> Function(int)>('malloc');
static final _free = _lib.lookupFunction<Void Function(Pointer<Void>), void Function(Pointer<Void>)>('free');
@override
Pointer<T> allocate<T extends NativeType>(int byteCount, {int? alignment}) => _malloc(byteCount).cast();
@override
void free(Pointer pointer) => _free(pointer.cast());
}
final libc = Libc();
void main() {
final p = libc<Uint16>(4);
for (var i = 0; i < 4; i++) {
p[i] = [1000, 2000, 65000, 65535][i];
}
final q = p + 3;
print('(p + 3).value: ${q.value}');
print('bytes between p, p+3: ${q.address - p.address}');
print('(p + 1)[1] == p[2]: ${(p + 1)[1] == p[2]}');
libc.free(p);
}(p + 3).value: 65535 bytes between p, p+3: 6 (p + 1)[1] == p[2]: true
Pointer<Uint16> operator -(int offset)A pointer to the offsetth Uint16 before this one.
Equivalent to this + (-offset).
Returns a pointer to the Uint16 whose address is offset times the size of Uint16 before the address of this pointer. That is, (this - offset).address == this.address - offset * sizeOf<Uint16>.
Also, (this - offset).value is equivalent to this[-offset], and similarly for setting,
import 'raya:ffi';
// A tiny allocator over the C library's malloc and free.
final class Libc implements Allocator {
static final _lib = DynamicLibrary.process();
static final _malloc = _lib.lookupFunction<Pointer<Void> Function(IntPtr), Pointer<Void> Function(int)>('malloc');
static final _free = _lib.lookupFunction<Void Function(Pointer<Void>), void Function(Pointer<Void>)>('free');
@override
Pointer<T> allocate<T extends NativeType>(int byteCount, {int? alignment}) => _malloc(byteCount).cast();
@override
void free(Pointer pointer) => _free(pointer.cast());
}
final libc = Libc();
void main() {
final p = libc<Uint16>(4);
for (var i = 0; i < 4; i++) {
p[i] = [1000, 2000, 65000, 65535][i];
}
final end = p + 4; // one past the last element
print('(end - 1).value: ${(end - 1).value}');
print('end - 4 == p: ${end - 4 == p}');
print('bytes from end - 2: ${end.address - (end - 2).address}');
libc.free(p);
}(end - 1).value: 65535 end - 4 == p: true bytes from end - 2: 4
Uint32Pointer
extension Uint32Pointer on Pointer<Uint32>
Properties
external int get valueThe 32-bit unsigned integer at address.
A Raya integer is truncated to 32 bits (as if by .toUnsigned(32)) before being stored, and the 32-bit value is zero-extended when it is loaded.
The address must be 4-byte aligned.
external void set value(int value)import 'raya:ffi';
// A tiny allocator over the C library's malloc and free.
final class Libc implements Allocator {
static final _lib = DynamicLibrary.process();
static final _malloc = _lib.lookupFunction<Pointer<Void> Function(IntPtr), Pointer<Void> Function(int)>('malloc');
static final _free = _lib.lookupFunction<Void Function(Pointer<Void>), void Function(Pointer<Void>)>('free');
@override
Pointer<T> allocate<T extends NativeType>(int byteCount, {int? alignment}) => _malloc(byteCount).cast();
@override
void free(Pointer pointer) => _free(pointer.cast());
}
final libc = Libc();
void main() {
final p = libc<Uint32>();
p.value = 1;
print('stored 1: ${p.value}');
// Uint32 holds 0..4294967295, so -1 reads as the maximum.
p.value = -1;
print('stored -1: ${p.value}');
libc.free(p);
}stored 1: 1 stored -1: 4294967295
Methods
Pointer<Uint32> elementAt(int index)Pointer arithmetic (takes element size into account).
import 'raya:ffi';
// A tiny allocator over the C library's malloc and free.
final class Libc implements Allocator {
static final _lib = DynamicLibrary.process();
static final _malloc = _lib.lookupFunction<Pointer<Void> Function(IntPtr), Pointer<Void> Function(int)>('malloc');
static final _free = _lib.lookupFunction<Void Function(Pointer<Void>), void Function(Pointer<Void>)>('free');
@override
Pointer<T> allocate<T extends NativeType>(int byteCount, {int? alignment}) => _malloc(byteCount).cast();
@override
void free(Pointer pointer) => _free(pointer.cast());
}
final libc = Libc();
void main() {
final p = libc<Uint32>(4);
const values = [1, 1000000, 4000000000, 4294967295];
for (var i = 0; i < 4; i++) {
p.elementAt(i).value = values[i];
}
print('element 2: ${p.elementAt(2).value}');
print('byte offset of 3: ${p.elementAt(3).address - p.address}');
print('sizeOf<Uint32>(): ${sizeOf<Uint32>()}');
libc.free(p);
}element 2: 4000000000 byte offset of 3: 12 sizeOf<Uint32>(): 4
external Uint32List asTypedList(int length, {@Since('3.1') Pointer<NativeFinalizerFunction>? finalizer, @Since('3.1') Pointer<Void>? token})Creates a typed list view backed by memory in the address space.
The returned view will allow access to the memory range from address to address + sizeOf<Uint32> * length.
The user has to ensure the memory range is accessible while using the returned list.
If provided, finalizer will be run on the pointer once the typed list is GCed. If provided, token will be passed to finalizer, otherwise the this pointer itself will be passed.
The address must be 4-byte aligned.
import 'raya:ffi';
// A tiny allocator over the C library's malloc and free.
final class Libc implements Allocator {
static final _lib = DynamicLibrary.process();
static final _malloc = _lib.lookupFunction<Pointer<Void> Function(IntPtr), Pointer<Void> Function(int)>('malloc');
static final _free = _lib.lookupFunction<Void Function(Pointer<Void>), void Function(Pointer<Void>)>('free');
@override
Pointer<T> allocate<T extends NativeType>(int byteCount, {int? alignment}) => _malloc(byteCount).cast();
@override
void free(Pointer pointer) => _free(pointer.cast());
}
final libc = Libc();
void main() {
final p = libc<Uint32>(4);
final view = p.asTypedList(4);
view.setAll(0, [1, 1000000, 4000000000, 4294967295]);
print('view: $view');
print('pointer [3]: ${p[3]}');
// The list and the pointer share the same native memory.
p[0] = -1;
print('after p[0] = -1: view[0] = ${view[0]}');
print('Uint32List length ${view.length}, ${view.lengthInBytes} bytes');
libc.free(p);
}view: [1, 1000000, 4000000000, 4294967295] pointer [3]: 4294967295 after p[0] = -1: view[0] = 4294967295 Uint32List length 4, 16 bytes
Operators
external int operator [](int index)The 32-bit unsigned integer at address + sizeOf<Uint32> * index.
A Raya integer is truncated to 32 bits (as if by .toUnsigned(32)) before being stored, and the 32-bit value is zero-extended when it is loaded.
The address must be 4-byte aligned.
import 'raya:ffi';
// A tiny allocator over the C library's malloc and free.
final class Libc implements Allocator {
static final _lib = DynamicLibrary.process();
static final _malloc = _lib.lookupFunction<Pointer<Void> Function(IntPtr), Pointer<Void> Function(int)>('malloc');
static final _free = _lib.lookupFunction<Void Function(Pointer<Void>), void Function(Pointer<Void>)>('free');
@override
Pointer<T> allocate<T extends NativeType>(int byteCount, {int? alignment}) => _malloc(byteCount).cast();
@override
void free(Pointer pointer) => _free(pointer.cast());
}
final libc = Libc();
void main() {
final p = libc<Uint32>(4);
const values = [1, 1000000, 4000000000, 4294967295];
for (var i = 0; i < 4; i++) {
p[i] = values[i];
}
print('p[0]: ${p[0]}, p[3]: ${p[3]}');
var sum = 0;
for (var i = 0; i < 4; i++) {
sum += p[i];
}
print('sum: $sum');
libc.free(p);
}p[0]: 1, p[3]: 4294967295 sum: 8295967296
external void operator []=(int index, int value)The 32-bit unsigned integer at address + sizeOf<Uint32> * index.
A Raya integer is truncated to 32 bits (as if by .toUnsigned(32)) before being stored, and the 32-bit value is zero-extended when it is loaded.
The address must be 4-byte aligned.
import 'raya:ffi';
// A tiny allocator over the C library's malloc and free.
final class Libc implements Allocator {
static final _lib = DynamicLibrary.process();
static final _malloc = _lib.lookupFunction<Pointer<Void> Function(IntPtr), Pointer<Void> Function(int)>('malloc');
static final _free = _lib.lookupFunction<Void Function(Pointer<Void>), void Function(Pointer<Void>)>('free');
@override
Pointer<T> allocate<T extends NativeType>(int byteCount, {int? alignment}) => _malloc(byteCount).cast();
@override
void free(Pointer pointer) => _free(pointer.cast());
}
final libc = Libc();
void main() {
final p = libc<Uint32>(3);
p[0] = 1000000;
p[1] = 4000000000;
// Uint32 holds 0..4294967295, so -1 reads as the maximum.
p[2] = -1;
print('p[0] = ${p[0]}');
print('p[1] = ${p[1]}');
print('p[2] = ${p[2]} (stored -1)');
libc.free(p);
}p[0] = 1000000 p[1] = 4000000000 p[2] = 4294967295 (stored -1)
Pointer<Uint32> operator +(int offset)A pointer to the offsetth Uint32 after this one.
Returns a pointer to the Uint32 whose address is offset times the size of Uint32 after the address of this pointer. That is (this + offset).address == this.address + offset * sizeOf<Uint32>.
Also (this + offset).value is equivalent to this[offset], and similarly for setting.
import 'raya:ffi';
// A tiny allocator over the C library's malloc and free.
final class Libc implements Allocator {
static final _lib = DynamicLibrary.process();
static final _malloc = _lib.lookupFunction<Pointer<Void> Function(IntPtr), Pointer<Void> Function(int)>('malloc');
static final _free = _lib.lookupFunction<Void Function(Pointer<Void>), void Function(Pointer<Void>)>('free');
@override
Pointer<T> allocate<T extends NativeType>(int byteCount, {int? alignment}) => _malloc(byteCount).cast();
@override
void free(Pointer pointer) => _free(pointer.cast());
}
final libc = Libc();
void main() {
final p = libc<Uint32>(4);
for (var i = 0; i < 4; i++) {
p[i] = [1, 1000000, 4000000000, 4294967295][i];
}
final q = p + 3;
print('(p + 3).value: ${q.value}');
print('bytes between p, p+3: ${q.address - p.address}');
print('(p + 1)[1] == p[2]: ${(p + 1)[1] == p[2]}');
libc.free(p);
}(p + 3).value: 4294967295 bytes between p, p+3: 12 (p + 1)[1] == p[2]: true
Pointer<Uint32> operator -(int offset)A pointer to the offsetth Uint32 before this one.
Equivalent to this + (-offset).
Returns a pointer to the Uint32 whose address is offset times the size of Uint32 before the address of this pointer. That is, (this - offset).address == this.address - offset * sizeOf<Uint32>.
Also, (this - offset).value is equivalent to this[-offset], and similarly for setting,
import 'raya:ffi';
// A tiny allocator over the C library's malloc and free.
final class Libc implements Allocator {
static final _lib = DynamicLibrary.process();
static final _malloc = _lib.lookupFunction<Pointer<Void> Function(IntPtr), Pointer<Void> Function(int)>('malloc');
static final _free = _lib.lookupFunction<Void Function(Pointer<Void>), void Function(Pointer<Void>)>('free');
@override
Pointer<T> allocate<T extends NativeType>(int byteCount, {int? alignment}) => _malloc(byteCount).cast();
@override
void free(Pointer pointer) => _free(pointer.cast());
}
final libc = Libc();
void main() {
final p = libc<Uint32>(4);
for (var i = 0; i < 4; i++) {
p[i] = [1, 1000000, 4000000000, 4294967295][i];
}
final end = p + 4; // one past the last element
print('(end - 1).value: ${(end - 1).value}');
print('end - 4 == p: ${end - 4 == p}');
print('bytes from end - 2: ${end.address - (end - 2).address}');
libc.free(p);
}(end - 1).value: 4294967295 end - 4 == p: true bytes from end - 2: 8
Uint64Pointer
extension Uint64Pointer on Pointer<Uint64>
Properties
external int get valueThe 64-bit unsigned integer at address.
The address must be 8-byte aligned.
external void set value(int value)import 'raya:ffi';
// A tiny allocator over the C library's malloc and free.
final class Libc implements Allocator {
static final _lib = DynamicLibrary.process();
static final _malloc = _lib.lookupFunction<Pointer<Void> Function(IntPtr), Pointer<Void> Function(int)>('malloc');
static final _free = _lib.lookupFunction<Void Function(Pointer<Void>), void Function(Pointer<Void>)>('free');
@override
Pointer<T> allocate<T extends NativeType>(int byteCount, {int? alignment}) => _malloc(byteCount).cast();
@override
void free(Pointer pointer) => _free(pointer.cast());
}
final libc = Libc();
void main() {
final p = libc<Uint64>();
p.value = 1;
print('stored 1: ${p.value}');
// Uint64 shares int's 64 bits: -1 is stored as all ones.
p.value = -1;
print('stored -1: ${p.value}');
print('as unsigned: ${BigInt.from(p.value).toUnsigned(64)}');
libc.free(p);
}stored 1: 1 stored -1: -1 as unsigned: 18446744073709551615
Methods
Pointer<Uint64> elementAt(int index)Pointer arithmetic (takes element size into account).
import 'raya:ffi';
// A tiny allocator over the C library's malloc and free.
final class Libc implements Allocator {
static final _lib = DynamicLibrary.process();
static final _malloc = _lib.lookupFunction<Pointer<Void> Function(IntPtr), Pointer<Void> Function(int)>('malloc');
static final _free = _lib.lookupFunction<Void Function(Pointer<Void>), void Function(Pointer<Void>)>('free');
@override
Pointer<T> allocate<T extends NativeType>(int byteCount, {int? alignment}) => _malloc(byteCount).cast();
@override
void free(Pointer pointer) => _free(pointer.cast());
}
final libc = Libc();
void main() {
final p = libc<Uint64>(4);
const values = [1, 1099511627776, 4611686018427387904, 12345];
for (var i = 0; i < 4; i++) {
p.elementAt(i).value = values[i];
}
print('element 2: ${p.elementAt(2).value}');
print('byte offset of 3: ${p.elementAt(3).address - p.address}');
print('sizeOf<Uint64>(): ${sizeOf<Uint64>()}');
libc.free(p);
}element 2: 4611686018427387904 byte offset of 3: 24 sizeOf<Uint64>(): 8
external Uint64List asTypedList(int length, {@Since('3.1') Pointer<NativeFinalizerFunction>? finalizer, @Since('3.1') Pointer<Void>? token})Creates a typed list view backed by memory in the address space.
The returned view will allow access to the memory range from address to address + sizeOf<Uint64> * length.
The user has to ensure the memory range is accessible while using the returned list.
If provided, finalizer will be run on the pointer once the typed list is GCed. If provided, token will be passed to finalizer, otherwise the this pointer itself will be passed.
The address must be 8-byte aligned.
import 'raya:ffi';
// A tiny allocator over the C library's malloc and free.
final class Libc implements Allocator {
static final _lib = DynamicLibrary.process();
static final _malloc = _lib.lookupFunction<Pointer<Void> Function(IntPtr), Pointer<Void> Function(int)>('malloc');
static final _free = _lib.lookupFunction<Void Function(Pointer<Void>), void Function(Pointer<Void>)>('free');
@override
Pointer<T> allocate<T extends NativeType>(int byteCount, {int? alignment}) => _malloc(byteCount).cast();
@override
void free(Pointer pointer) => _free(pointer.cast());
}
final libc = Libc();
void main() {
final p = libc<Uint64>(4);
final view = p.asTypedList(4);
view.setAll(0, [1, 1099511627776, 4611686018427387904, 12345]);
print('view: $view');
print('pointer [3]: ${p[3]}');
// The list and the pointer share the same native memory.
p[0] = -1;
print('after p[0] = -1: view[0] = ${view[0]}');
print('Uint64List length ${view.length}, ${view.lengthInBytes} bytes');
libc.free(p);
}view: [1, 1099511627776, 4611686018427387904, 12345] pointer [3]: 12345 after p[0] = -1: view[0] = -1 Uint64List length 4, 32 bytes
Operators
external int operator [](int index)The 64-bit unsigned integer at address + sizeOf<Uint64> * index.
The address must be 8-byte aligned.
import 'raya:ffi';
// A tiny allocator over the C library's malloc and free.
final class Libc implements Allocator {
static final _lib = DynamicLibrary.process();
static final _malloc = _lib.lookupFunction<Pointer<Void> Function(IntPtr), Pointer<Void> Function(int)>('malloc');
static final _free = _lib.lookupFunction<Void Function(Pointer<Void>), void Function(Pointer<Void>)>('free');
@override
Pointer<T> allocate<T extends NativeType>(int byteCount, {int? alignment}) => _malloc(byteCount).cast();
@override
void free(Pointer pointer) => _free(pointer.cast());
}
final libc = Libc();
void main() {
final p = libc<Uint64>(4);
const values = [1, 1099511627776, 4611686018427387904, 12345];
for (var i = 0; i < 4; i++) {
p[i] = values[i];
}
print('p[0]: ${p[0]}, p[3]: ${p[3]}');
var sum = 0;
for (var i = 0; i < 4; i++) {
sum += p[i];
}
print('sum: $sum');
libc.free(p);
}p[0]: 1, p[3]: 12345 sum: 4611687117939028026
external void operator []=(int index, int value)The 64-bit unsigned integer at address + sizeOf<Uint64> * index.
The address must be 8-byte aligned.
import 'raya:ffi';
// A tiny allocator over the C library's malloc and free.
final class Libc implements Allocator {
static final _lib = DynamicLibrary.process();
static final _malloc = _lib.lookupFunction<Pointer<Void> Function(IntPtr), Pointer<Void> Function(int)>('malloc');
static final _free = _lib.lookupFunction<Void Function(Pointer<Void>), void Function(Pointer<Void>)>('free');
@override
Pointer<T> allocate<T extends NativeType>(int byteCount, {int? alignment}) => _malloc(byteCount).cast();
@override
void free(Pointer pointer) => _free(pointer.cast());
}
final libc = Libc();
void main() {
final p = libc<Uint64>(3);
p[0] = 1099511627776;
p[1] = 4611686018427387904;
// Uint64 shares int's 64 bits: -1 is stored as all ones.
p[2] = -1;
print('p[0] = ${p[0]}');
print('p[1] = ${p[1]}');
print('p[2] = ${p[2]} (stored -1)');
libc.free(p);
}p[0] = 1099511627776 p[1] = 4611686018427387904 p[2] = -1 (stored -1)
Pointer<Uint64> operator +(int offset)A pointer to the offsetth Uint64 after this one.
Returns a pointer to the Uint64 whose address is offset times the size of Uint64 after the address of this pointer. That is (this + offset).address == this.address + offset * sizeOf<Uint64>.
Also (this + offset).value is equivalent to this[offset], and similarly for setting.
import 'raya:ffi';
// A tiny allocator over the C library's malloc and free.
final class Libc implements Allocator {
static final _lib = DynamicLibrary.process();
static final _malloc = _lib.lookupFunction<Pointer<Void> Function(IntPtr), Pointer<Void> Function(int)>('malloc');
static final _free = _lib.lookupFunction<Void Function(Pointer<Void>), void Function(Pointer<Void>)>('free');
@override
Pointer<T> allocate<T extends NativeType>(int byteCount, {int? alignment}) => _malloc(byteCount).cast();
@override
void free(Pointer pointer) => _free(pointer.cast());
}
final libc = Libc();
void main() {
final p = libc<Uint64>(4);
for (var i = 0; i < 4; i++) {
p[i] = [1, 1099511627776, 4611686018427387904, 12345][i];
}
final q = p + 3;
print('(p + 3).value: ${q.value}');
print('bytes between p, p+3: ${q.address - p.address}');
print('(p + 1)[1] == p[2]: ${(p + 1)[1] == p[2]}');
libc.free(p);
}(p + 3).value: 12345 bytes between p, p+3: 24 (p + 1)[1] == p[2]: true
Pointer<Uint64> operator -(int offset)A pointer to the offsetth Uint64 before this one.
Equivalent to this + (-offset).
Returns a pointer to the Uint64 whose address is offset times the size of Uint64 before the address of this pointer. That is, (this - offset).address == this.address - offset * sizeOf<Uint64>.
Also, (this - offset).value is equivalent to this[-offset], and similarly for setting,
import 'raya:ffi';
// A tiny allocator over the C library's malloc and free.
final class Libc implements Allocator {
static final _lib = DynamicLibrary.process();
static final _malloc = _lib.lookupFunction<Pointer<Void> Function(IntPtr), Pointer<Void> Function(int)>('malloc');
static final _free = _lib.lookupFunction<Void Function(Pointer<Void>), void Function(Pointer<Void>)>('free');
@override
Pointer<T> allocate<T extends NativeType>(int byteCount, {int? alignment}) => _malloc(byteCount).cast();
@override
void free(Pointer pointer) => _free(pointer.cast());
}
final libc = Libc();
void main() {
final p = libc<Uint64>(4);
for (var i = 0; i < 4; i++) {
p[i] = [1, 1099511627776, 4611686018427387904, 12345][i];
}
final end = p + 4; // one past the last element
print('(end - 1).value: ${(end - 1).value}');
print('end - 4 == p: ${end - 4 == p}');
print('bytes from end - 2: ${end.address - (end - 2).address}');
libc.free(p);
}(end - 1).value: 12345 end - 4 == p: true bytes from end - 2: 16
FloatPointer
extension FloatPointer on Pointer<Float>
Properties
external double get valueThe float at address.
A Raya double loses precision before being stored, and the float value is converted to a double when it is loaded.
The address must be 4-byte aligned.
external void set value(double value)import 'raya:ffi';
// A tiny allocator over the C library's malloc and free.
final class Libc implements Allocator {
static final _lib = DynamicLibrary.process();
static final _malloc = _lib.lookupFunction<Pointer<Void> Function(IntPtr), Pointer<Void> Function(int)>('malloc');
static final _free = _lib.lookupFunction<Void Function(Pointer<Void>), void Function(Pointer<Void>)>('free');
@override
Pointer<T> allocate<T extends NativeType>(int byteCount, {int? alignment}) => _malloc(byteCount).cast();
@override
void free(Pointer pointer) => _free(pointer.cast());
}
final libc = Libc();
void main() {
final p = libc<Float>();
p.value = 0.5;
print('stored 0.5: ${p.value}');
// Float is 32-bit, so 0.1 comes back rounded.
p.value = 0.1;
print('stored 0.1: ${p.value}');
libc.free(p);
}stored 0.5: 0.5 stored 0.1: 0.10000000149011612
Methods
Pointer<Float> elementAt(int index)Pointer arithmetic (takes element size into account).
import 'raya:ffi';
// A tiny allocator over the C library's malloc and free.
final class Libc implements Allocator {
static final _lib = DynamicLibrary.process();
static final _malloc = _lib.lookupFunction<Pointer<Void> Function(IntPtr), Pointer<Void> Function(int)>('malloc');
static final _free = _lib.lookupFunction<Void Function(Pointer<Void>), void Function(Pointer<Void>)>('free');
@override
Pointer<T> allocate<T extends NativeType>(int byteCount, {int? alignment}) => _malloc(byteCount).cast();
@override
void free(Pointer pointer) => _free(pointer.cast());
}
final libc = Libc();
void main() {
final p = libc<Float>(4);
const values = [0.5, 1.25, -2.0, 3.75];
for (var i = 0; i < 4; i++) {
p.elementAt(i).value = values[i];
}
print('element 2: ${p.elementAt(2).value}');
print('byte offset of 3: ${p.elementAt(3).address - p.address}');
print('sizeOf<Float>(): ${sizeOf<Float>()}');
libc.free(p);
}element 2: -2.0 byte offset of 3: 12 sizeOf<Float>(): 4
external Float32List asTypedList(int length, {@Since('3.1') Pointer<NativeFinalizerFunction>? finalizer, @Since('3.1') Pointer<Void>? token})Creates a typed list view backed by memory in the address space.
The returned view will allow access to the memory range from address to address + sizeOf<Float> * length.
The user has to ensure the memory range is accessible while using the returned list.
If provided, finalizer will be run on the pointer once the typed list is GCed. If provided, token will be passed to finalizer, otherwise the this pointer itself will be passed.
The address must be 4-byte aligned.
import 'raya:ffi';
// A tiny allocator over the C library's malloc and free.
final class Libc implements Allocator {
static final _lib = DynamicLibrary.process();
static final _malloc = _lib.lookupFunction<Pointer<Void> Function(IntPtr), Pointer<Void> Function(int)>('malloc');
static final _free = _lib.lookupFunction<Void Function(Pointer<Void>), void Function(Pointer<Void>)>('free');
@override
Pointer<T> allocate<T extends NativeType>(int byteCount, {int? alignment}) => _malloc(byteCount).cast();
@override
void free(Pointer pointer) => _free(pointer.cast());
}
final libc = Libc();
void main() {
final p = libc<Float>(4);
final view = p.asTypedList(4);
view.setAll(0, [0.5, 1.25, -2.0, 3.75]);
print('view: $view');
print('pointer [3]: ${p[3]}');
// The list and the pointer share the same native memory.
p[0] = 0.1;
print('after p[0] = 0.1: view[0] = ${view[0]}');
print('Float32List length ${view.length}, ${view.lengthInBytes} bytes');
libc.free(p);
}view: [0.5, 1.25, -2.0, 3.75] pointer [3]: 3.75 after p[0] = 0.1: view[0] = 0.10000000149011612 Float32List length 4, 16 bytes
Operators
external double operator [](int index)The float at address + sizeOf<Float> * index.
A Raya double loses precision before being stored, and the float value is converted to a double when it is loaded.
The address must be 4-byte aligned.
import 'raya:ffi';
// A tiny allocator over the C library's malloc and free.
final class Libc implements Allocator {
static final _lib = DynamicLibrary.process();
static final _malloc = _lib.lookupFunction<Pointer<Void> Function(IntPtr), Pointer<Void> Function(int)>('malloc');
static final _free = _lib.lookupFunction<Void Function(Pointer<Void>), void Function(Pointer<Void>)>('free');
@override
Pointer<T> allocate<T extends NativeType>(int byteCount, {int? alignment}) => _malloc(byteCount).cast();
@override
void free(Pointer pointer) => _free(pointer.cast());
}
final libc = Libc();
void main() {
final p = libc<Float>(4);
const values = [0.5, 1.25, -2.0, 3.75];
for (var i = 0; i < 4; i++) {
p[i] = values[i];
}
print('p[0]: ${p[0]}, p[3]: ${p[3]}');
var sum = 0.0;
for (var i = 0; i < 4; i++) {
sum += p[i];
}
print('sum: $sum');
libc.free(p);
}p[0]: 0.5, p[3]: 3.75 sum: 3.5
external void operator []=(int index, double value)The float at address + sizeOf<Float> * index.
A Raya double loses precision before being stored, and the float value is converted to a double when it is loaded.
The address must be 4-byte aligned.
import 'raya:ffi';
// A tiny allocator over the C library's malloc and free.
final class Libc implements Allocator {
static final _lib = DynamicLibrary.process();
static final _malloc = _lib.lookupFunction<Pointer<Void> Function(IntPtr), Pointer<Void> Function(int)>('malloc');
static final _free = _lib.lookupFunction<Void Function(Pointer<Void>), void Function(Pointer<Void>)>('free');
@override
Pointer<T> allocate<T extends NativeType>(int byteCount, {int? alignment}) => _malloc(byteCount).cast();
@override
void free(Pointer pointer) => _free(pointer.cast());
}
final libc = Libc();
void main() {
final p = libc<Float>(3);
p[0] = 1.25;
p[1] = -2.0;
// Float is 32-bit, so 0.1 comes back rounded.
p[2] = 0.1;
print('p[0] = ${p[0]}');
print('p[1] = ${p[1]}');
print('p[2] = ${p[2]} (stored 0.1)');
libc.free(p);
}p[0] = 1.25 p[1] = -2.0 p[2] = 0.10000000149011612 (stored 0.1)
Pointer<Float> operator +(int offset)A pointer to the offsetth Float after this one.
Returns a pointer to the Float whose address is offset times the size of Float after the address of this pointer. That is (this + offset).address == this.address + offset * sizeOf<Float>.
Also (this + offset).value is equivalent to this[offset], and similarly for setting.
import 'raya:ffi';
// A tiny allocator over the C library's malloc and free.
final class Libc implements Allocator {
static final _lib = DynamicLibrary.process();
static final _malloc = _lib.lookupFunction<Pointer<Void> Function(IntPtr), Pointer<Void> Function(int)>('malloc');
static final _free = _lib.lookupFunction<Void Function(Pointer<Void>), void Function(Pointer<Void>)>('free');
@override
Pointer<T> allocate<T extends NativeType>(int byteCount, {int? alignment}) => _malloc(byteCount).cast();
@override
void free(Pointer pointer) => _free(pointer.cast());
}
final libc = Libc();
void main() {
final p = libc<Float>(4);
for (var i = 0; i < 4; i++) {
p[i] = [0.5, 1.25, -2.0, 3.75][i];
}
final q = p + 3;
print('(p + 3).value: ${q.value}');
print('bytes between p, p+3: ${q.address - p.address}');
print('(p + 1)[1] == p[2]: ${(p + 1)[1] == p[2]}');
libc.free(p);
}(p + 3).value: 3.75 bytes between p, p+3: 12 (p + 1)[1] == p[2]: true
Pointer<Float> operator -(int offset)A pointer to the offsetth Float before this one.
Equivalent to this + (-offset).
Returns a pointer to the Float whose address is offset times the size of Float before the address of this pointer. That is, (this - offset).address == this.address - offset * sizeOf<Float>.
Also, (this - offset).value is equivalent to this[-offset], and similarly for setting,
import 'raya:ffi';
// A tiny allocator over the C library's malloc and free.
final class Libc implements Allocator {
static final _lib = DynamicLibrary.process();
static final _malloc = _lib.lookupFunction<Pointer<Void> Function(IntPtr), Pointer<Void> Function(int)>('malloc');
static final _free = _lib.lookupFunction<Void Function(Pointer<Void>), void Function(Pointer<Void>)>('free');
@override
Pointer<T> allocate<T extends NativeType>(int byteCount, {int? alignment}) => _malloc(byteCount).cast();
@override
void free(Pointer pointer) => _free(pointer.cast());
}
final libc = Libc();
void main() {
final p = libc<Float>(4);
for (var i = 0; i < 4; i++) {
p[i] = [0.5, 1.25, -2.0, 3.75][i];
}
final end = p + 4; // one past the last element
print('(end - 1).value: ${(end - 1).value}');
print('end - 4 == p: ${end - 4 == p}');
print('bytes from end - 2: ${end.address - (end - 2).address}');
libc.free(p);
}(end - 1).value: 3.75 end - 4 == p: true bytes from end - 2: 8
DoublePointer
extension DoublePointer on Pointer<Double>
Properties
external void set value(double value)import 'raya:ffi';
// A tiny allocator over the C library's malloc and free.
final class Libc implements Allocator {
static final _lib = DynamicLibrary.process();
static final _malloc = _lib.lookupFunction<Pointer<Void> Function(IntPtr), Pointer<Void> Function(int)>('malloc');
static final _free = _lib.lookupFunction<Void Function(Pointer<Void>), void Function(Pointer<Void>)>('free');
@override
Pointer<T> allocate<T extends NativeType>(int byteCount, {int? alignment}) => _malloc(byteCount).cast();
@override
void free(Pointer pointer) => _free(pointer.cast());
}
final libc = Libc();
void main() {
final p = libc<Double>();
p.value = 0.5;
print('stored 0.5: ${p.value}');
// Double is 64-bit, so 0.1 comes back exactly as written.
p.value = 0.1;
print('stored 0.1: ${p.value}');
libc.free(p);
}stored 0.5: 0.5 stored 0.1: 0.1
Methods
Pointer<Double> elementAt(int index)Pointer arithmetic (takes element size into account).
import 'raya:ffi';
// A tiny allocator over the C library's malloc and free.
final class Libc implements Allocator {
static final _lib = DynamicLibrary.process();
static final _malloc = _lib.lookupFunction<Pointer<Void> Function(IntPtr), Pointer<Void> Function(int)>('malloc');
static final _free = _lib.lookupFunction<Void Function(Pointer<Void>), void Function(Pointer<Void>)>('free');
@override
Pointer<T> allocate<T extends NativeType>(int byteCount, {int? alignment}) => _malloc(byteCount).cast();
@override
void free(Pointer pointer) => _free(pointer.cast());
}
final libc = Libc();
void main() {
final p = libc<Double>(4);
const values = [0.5, 1.25, -2.0, 3.75];
for (var i = 0; i < 4; i++) {
p.elementAt(i).value = values[i];
}
print('element 2: ${p.elementAt(2).value}');
print('byte offset of 3: ${p.elementAt(3).address - p.address}');
print('sizeOf<Double>(): ${sizeOf<Double>()}');
libc.free(p);
}element 2: -2.0 byte offset of 3: 24 sizeOf<Double>(): 8
external Float64List asTypedList(int length, {@Since('3.1') Pointer<NativeFinalizerFunction>? finalizer, @Since('3.1') Pointer<Void>? token})Creates a typed list view backed by memory in the address space.
The returned view will allow access to the memory range from address to address + sizeOf<Double> * length.
The user has to ensure the memory range is accessible while using the returned list.
If provided, finalizer will be run on the pointer once the typed list is GCed. If provided, token will be passed to finalizer, otherwise the this pointer itself will be passed.
The address must be 8-byte aligned.
import 'raya:ffi';
// A tiny allocator over the C library's malloc and free.
final class Libc implements Allocator {
static final _lib = DynamicLibrary.process();
static final _malloc = _lib.lookupFunction<Pointer<Void> Function(IntPtr), Pointer<Void> Function(int)>('malloc');
static final _free = _lib.lookupFunction<Void Function(Pointer<Void>), void Function(Pointer<Void>)>('free');
@override
Pointer<T> allocate<T extends NativeType>(int byteCount, {int? alignment}) => _malloc(byteCount).cast();
@override
void free(Pointer pointer) => _free(pointer.cast());
}
final libc = Libc();
void main() {
final p = libc<Double>(4);
final view = p.asTypedList(4);
view.setAll(0, [0.5, 1.25, -2.0, 3.75]);
print('view: $view');
print('pointer [3]: ${p[3]}');
// The list and the pointer share the same native memory.
p[0] = 0.1;
print('after p[0] = 0.1: view[0] = ${view[0]}');
print('Float64List length ${view.length}, ${view.lengthInBytes} bytes');
libc.free(p);
}view: [0.5, 1.25, -2.0, 3.75] pointer [3]: 3.75 after p[0] = 0.1: view[0] = 0.1 Float64List length 4, 32 bytes
Operators
external double operator [](int index)The double at address + sizeOf<Double> * index.
The address must be 8-byte aligned.
import 'raya:ffi';
// A tiny allocator over the C library's malloc and free.
final class Libc implements Allocator {
static final _lib = DynamicLibrary.process();
static final _malloc = _lib.lookupFunction<Pointer<Void> Function(IntPtr), Pointer<Void> Function(int)>('malloc');
static final _free = _lib.lookupFunction<Void Function(Pointer<Void>), void Function(Pointer<Void>)>('free');
@override
Pointer<T> allocate<T extends NativeType>(int byteCount, {int? alignment}) => _malloc(byteCount).cast();
@override
void free(Pointer pointer) => _free(pointer.cast());
}
final libc = Libc();
void main() {
final p = libc<Double>(4);
const values = [0.5, 1.25, -2.0, 3.75];
for (var i = 0; i < 4; i++) {
p[i] = values[i];
}
print('p[0]: ${p[0]}, p[3]: ${p[3]}');
var sum = 0.0;
for (var i = 0; i < 4; i++) {
sum += p[i];
}
print('sum: $sum');
libc.free(p);
}p[0]: 0.5, p[3]: 3.75 sum: 3.5
external void operator []=(int index, double value)The double at address + sizeOf<Double> * index.
The address must be 8-byte aligned.
import 'raya:ffi';
// A tiny allocator over the C library's malloc and free.
final class Libc implements Allocator {
static final _lib = DynamicLibrary.process();
static final _malloc = _lib.lookupFunction<Pointer<Void> Function(IntPtr), Pointer<Void> Function(int)>('malloc');
static final _free = _lib.lookupFunction<Void Function(Pointer<Void>), void Function(Pointer<Void>)>('free');
@override
Pointer<T> allocate<T extends NativeType>(int byteCount, {int? alignment}) => _malloc(byteCount).cast();
@override
void free(Pointer pointer) => _free(pointer.cast());
}
final libc = Libc();
void main() {
final p = libc<Double>(3);
p[0] = 1.25;
p[1] = -2.0;
// Double is 64-bit, so 0.1 comes back exactly as written.
p[2] = 0.1;
print('p[0] = ${p[0]}');
print('p[1] = ${p[1]}');
print('p[2] = ${p[2]} (stored 0.1)');
libc.free(p);
}p[0] = 1.25 p[1] = -2.0 p[2] = 0.1 (stored 0.1)
Pointer<Double> operator +(int offset)A pointer to the offsetth Double after this one.
Returns a pointer to the Double whose address is offset times the size of Double after the address of this pointer. That is (this + offset).address == this.address + offset * sizeOf<Double>.
Also (this + offset).value is equivalent to this[offset], and similarly for setting.
import 'raya:ffi';
// A tiny allocator over the C library's malloc and free.
final class Libc implements Allocator {
static final _lib = DynamicLibrary.process();
static final _malloc = _lib.lookupFunction<Pointer<Void> Function(IntPtr), Pointer<Void> Function(int)>('malloc');
static final _free = _lib.lookupFunction<Void Function(Pointer<Void>), void Function(Pointer<Void>)>('free');
@override
Pointer<T> allocate<T extends NativeType>(int byteCount, {int? alignment}) => _malloc(byteCount).cast();
@override
void free(Pointer pointer) => _free(pointer.cast());
}
final libc = Libc();
void main() {
final p = libc<Double>(4);
for (var i = 0; i < 4; i++) {
p[i] = [0.5, 1.25, -2.0, 3.75][i];
}
final q = p + 3;
print('(p + 3).value: ${q.value}');
print('bytes between p, p+3: ${q.address - p.address}');
print('(p + 1)[1] == p[2]: ${(p + 1)[1] == p[2]}');
libc.free(p);
}(p + 3).value: 3.75 bytes between p, p+3: 24 (p + 1)[1] == p[2]: true
Pointer<Double> operator -(int offset)A pointer to the offsetth Double before this one.
Equivalent to this + (-offset).
Returns a pointer to the Double whose address is offset times the size of Double before the address of this pointer. That is, (this - offset).address == this.address - offset * sizeOf<Double>.
Also, (this - offset).value is equivalent to this[-offset], and similarly for setting,
import 'raya:ffi';
// A tiny allocator over the C library's malloc and free.
final class Libc implements Allocator {
static final _lib = DynamicLibrary.process();
static final _malloc = _lib.lookupFunction<Pointer<Void> Function(IntPtr), Pointer<Void> Function(int)>('malloc');
static final _free = _lib.lookupFunction<Void Function(Pointer<Void>), void Function(Pointer<Void>)>('free');
@override
Pointer<T> allocate<T extends NativeType>(int byteCount, {int? alignment}) => _malloc(byteCount).cast();
@override
void free(Pointer pointer) => _free(pointer.cast());
}
final libc = Libc();
void main() {
final p = libc<Double>(4);
for (var i = 0; i < 4; i++) {
p[i] = [0.5, 1.25, -2.0, 3.75][i];
}
final end = p + 4; // one past the last element
print('(end - 1).value: ${(end - 1).value}');
print('end - 4 == p: ${end - 4 == p}');
print('bytes from end - 2: ${end.address - (end - 2).address}');
libc.free(p);
}(end - 1).value: 3.75 end - 4 == p: true bytes from end - 2: 16
BoolPointer
extension BoolPointer on Pointer<Bool>
Properties
external void set value(bool value)import 'raya:ffi';
// A tiny allocator over the C library's malloc and free.
final class Libc implements Allocator {
static final _lib = DynamicLibrary.process();
static final _malloc = _lib.lookupFunction<Pointer<Void> Function(IntPtr), Pointer<Void> Function(int)>('malloc');
static final _free = _lib.lookupFunction<Void Function(Pointer<Void>), void Function(Pointer<Void>)>('free');
@override
Pointer<T> allocate<T extends NativeType>(int byteCount, {int? alignment}) => _malloc(byteCount).cast();
@override
void free(Pointer pointer) => _free(pointer.cast());
}
final libc = Libc();
void main() {
final p = libc<Bool>();
p.value = true;
print('stored true: ${p.value}');
// Bool stores one byte per flag.
p.value = true;
print('stored true: ${p.value}');
libc.free(p);
}stored true: true stored true: true
Methods
Pointer<Bool> elementAt(int index)Pointer arithmetic (takes element size into account).
import 'raya:ffi';
// A tiny allocator over the C library's malloc and free.
final class Libc implements Allocator {
static final _lib = DynamicLibrary.process();
static final _malloc = _lib.lookupFunction<Pointer<Void> Function(IntPtr), Pointer<Void> Function(int)>('malloc');
static final _free = _lib.lookupFunction<Void Function(Pointer<Void>), void Function(Pointer<Void>)>('free');
@override
Pointer<T> allocate<T extends NativeType>(int byteCount, {int? alignment}) => _malloc(byteCount).cast();
@override
void free(Pointer pointer) => _free(pointer.cast());
}
final libc = Libc();
void main() {
final p = libc<Bool>(4);
const values = [true, false, true, true];
for (var i = 0; i < 4; i++) {
p.elementAt(i).value = values[i];
}
print('element 2: ${p.elementAt(2).value}');
print('byte offset of 3: ${p.elementAt(3).address - p.address}');
print('sizeOf<Bool>(): ${sizeOf<Bool>()}');
libc.free(p);
}element 2: true byte offset of 3: 3 sizeOf<Bool>(): 1
Operators
external bool operator [](int index)The bool at address + sizeOf<Bool> * index.
import 'raya:ffi';
// A tiny allocator over the C library's malloc and free.
final class Libc implements Allocator {
static final _lib = DynamicLibrary.process();
static final _malloc = _lib.lookupFunction<Pointer<Void> Function(IntPtr), Pointer<Void> Function(int)>('malloc');
static final _free = _lib.lookupFunction<Void Function(Pointer<Void>), void Function(Pointer<Void>)>('free');
@override
Pointer<T> allocate<T extends NativeType>(int byteCount, {int? alignment}) => _malloc(byteCount).cast();
@override
void free(Pointer pointer) => _free(pointer.cast());
}
final libc = Libc();
void main() {
final p = libc<Bool>(4);
const values = [true, false, true, true];
for (var i = 0; i < 4; i++) {
p[i] = values[i];
}
print('p[0]: ${p[0]}, p[3]: ${p[3]}');
var count = 0;
for (var i = 0; i < 4; i++) {
if (p[i]) count++;
}
print('true flags: $count of 4');
libc.free(p);
}p[0]: true, p[3]: true true flags: 3 of 4
external void operator []=(int index, bool value)The bool at address + sizeOf<Bool> * index.
import 'raya:ffi';
// A tiny allocator over the C library's malloc and free.
final class Libc implements Allocator {
static final _lib = DynamicLibrary.process();
static final _malloc = _lib.lookupFunction<Pointer<Void> Function(IntPtr), Pointer<Void> Function(int)>('malloc');
static final _free = _lib.lookupFunction<Void Function(Pointer<Void>), void Function(Pointer<Void>)>('free');
@override
Pointer<T> allocate<T extends NativeType>(int byteCount, {int? alignment}) => _malloc(byteCount).cast();
@override
void free(Pointer pointer) => _free(pointer.cast());
}
final libc = Libc();
void main() {
final p = libc<Bool>(3);
p[0] = false;
p[1] = true;
// Bool stores one byte per flag.
p[2] = true;
print('p[0] = ${p[0]}');
print('p[1] = ${p[1]}');
print('p[2] = ${p[2]} (stored true)');
libc.free(p);
}p[0] = false p[1] = true p[2] = true (stored true)
Pointer<Bool> operator +(int offset)A pointer to the offsetth Bool after this one.
Returns a pointer to the Bool whose address is offset times the size of Bool after the address of this pointer. That is (this + offset).address == this.address + offset * sizeOf<Bool>.
Also (this + offset).value is equivalent to this[offset], and similarly for setting.
import 'raya:ffi';
// A tiny allocator over the C library's malloc and free.
final class Libc implements Allocator {
static final _lib = DynamicLibrary.process();
static final _malloc = _lib.lookupFunction<Pointer<Void> Function(IntPtr), Pointer<Void> Function(int)>('malloc');
static final _free = _lib.lookupFunction<Void Function(Pointer<Void>), void Function(Pointer<Void>)>('free');
@override
Pointer<T> allocate<T extends NativeType>(int byteCount, {int? alignment}) => _malloc(byteCount).cast();
@override
void free(Pointer pointer) => _free(pointer.cast());
}
final libc = Libc();
void main() {
final p = libc<Bool>(4);
for (var i = 0; i < 4; i++) {
p[i] = [true, false, true, true][i];
}
final q = p + 3;
print('(p + 3).value: ${q.value}');
print('bytes between p, p+3: ${q.address - p.address}');
print('(p + 1)[1] == p[2]: ${(p + 1)[1] == p[2]}');
libc.free(p);
}(p + 3).value: true bytes between p, p+3: 3 (p + 1)[1] == p[2]: true
Pointer<Bool> operator -(int offset)A pointer to the offsetth Bool before this one.
Equivalent to this + (-offset).
Returns a pointer to the Bool whose address is offset times the size of Bool before the address of this pointer. That is, (this - offset).address == this.address - offset * sizeOf<Bool>.
Also, (this - offset).value is equivalent to this[-offset], and similarly for setting,
import 'raya:ffi';
// A tiny allocator over the C library's malloc and free.
final class Libc implements Allocator {
static final _lib = DynamicLibrary.process();
static final _malloc = _lib.lookupFunction<Pointer<Void> Function(IntPtr), Pointer<Void> Function(int)>('malloc');
static final _free = _lib.lookupFunction<Void Function(Pointer<Void>), void Function(Pointer<Void>)>('free');
@override
Pointer<T> allocate<T extends NativeType>(int byteCount, {int? alignment}) => _malloc(byteCount).cast();
@override
void free(Pointer pointer) => _free(pointer.cast());
}
final libc = Libc();
void main() {
final p = libc<Bool>(4);
for (var i = 0; i < 4; i++) {
p[i] = [true, false, true, true][i];
}
final end = p + 4; // one past the last element
print('(end - 1).value: ${(end - 1).value}');
print('end - 4 == p: ${end - 4 == p}');
print('bytes from end - 2: ${end.address - (end - 2).address}');
libc.free(p);
}(end - 1).value: true end - 4 == p: true bytes from end - 2: 2
Int8Array
extension Int8Array on Array<Int8>
Properties
external Int8List get elementsA list view of the bytes of this array.
Has the same length and elements (as accessed using the index operator) as this array, and writes to either the list or this arrary are visible in both.
Operators
external int operator [](int index)Loads a Raya value from this array at index.
This extension method must be invoked on a receiver of type Array<T> where T is a compile-time constant type.
import 'raya:ffi';
final class Row extends Struct {
@Array(4)
external Array<Int8> items;
}
void main() {
final row = Struct.create<Row>();
const values = [10, -20, 30, -40];
for (var i = 0; i < 4; i++) {
row.items[i] = values[i];
}
print('items[1]: ${row.items[1]}');
print('items[3]: ${row.items[3]}');
print('sizeOf<Row>(): ${sizeOf<Row>()} bytes (4 x ${sizeOf<Int8>()})');
}items[1]: -20 items[3]: -40 sizeOf<Row>(): 4 bytes (4 x 1)
external void operator []=(int index, int value)Stores a Raya value in this array at index.
This extension method must be invoked on a receiver of type Array<T> where T is a compile-time constant type.
import 'raya:ffi';
final class Row extends Struct {
@Array(4)
external Array<Int8> items;
}
void main() {
final row = Struct.create<Row>();
row.items[0] = 10;
row.items[1] = -40;
// Int8 holds -128..127, so 200 wraps.
row.items[2] = 200;
print('items[0] = ${row.items[0]}');
print('items[1] = ${row.items[1]}');
print('items[2] = ${row.items[2]} (stored 200)');
print('items[3] = ${row.items[3]} (never set)');
}items[0] = 10 items[1] = -40 items[2] = -56 (stored 200) items[3] = 0 (never set)
Int16Array
extension Int16Array on Array<Int16>
Properties
external Int16List get elementsA list view of the bytes of this array.
Has the same length and elements (as accessed using the index operator) as this array, and writes to either the list or this arrary are visible in both.
Operators
external int operator [](int index)Loads a Raya value from this array at index.
This extension method must be invoked on a receiver of type Array<T> where T is a compile-time constant type.
import 'raya:ffi';
final class Row extends Struct {
@Array(4)
external Array<Int16> items;
}
void main() {
final row = Struct.create<Row>();
const values = [1000, -2000, 3000, -4000];
for (var i = 0; i < 4; i++) {
row.items[i] = values[i];
}
print('items[1]: ${row.items[1]}');
print('items[3]: ${row.items[3]}');
print('sizeOf<Row>(): ${sizeOf<Row>()} bytes (4 x ${sizeOf<Int16>()})');
}items[1]: -2000 items[3]: -4000 sizeOf<Row>(): 8 bytes (4 x 2)
external void operator []=(int index, int value)Stores a Raya value in this array at index.
This extension method must be invoked on a receiver of type Array<T> where T is a compile-time constant type.
import 'raya:ffi';
final class Row extends Struct {
@Array(4)
external Array<Int16> items;
}
void main() {
final row = Struct.create<Row>();
row.items[0] = 1000;
row.items[1] = -4000;
// Int16 holds -32768..32767, so 40000 wraps.
row.items[2] = 40000;
print('items[0] = ${row.items[0]}');
print('items[1] = ${row.items[1]}');
print('items[2] = ${row.items[2]} (stored 40000)');
print('items[3] = ${row.items[3]} (never set)');
}items[0] = 1000 items[1] = -4000 items[2] = -25536 (stored 40000) items[3] = 0 (never set)
Int32Array
extension Int32Array on Array<Int32>
Properties
external Int32List get elementsA list view of the bytes of this array.
Has the same length and elements (as accessed using the index operator) as this array, and writes to either the list or this arrary are visible in both.
Operators
external int operator [](int index)Loads a Raya value from this array at index.
This extension method must be invoked on a receiver of type Array<T> where T is a compile-time constant type.
import 'raya:ffi';
final class Row extends Struct {
@Array(4)
external Array<Int32> items;
}
void main() {
final row = Struct.create<Row>();
const values = [100000, -200000, 300000, -400000];
for (var i = 0; i < 4; i++) {
row.items[i] = values[i];
}
print('items[1]: ${row.items[1]}');
print('items[3]: ${row.items[3]}');
print('sizeOf<Row>(): ${sizeOf<Row>()} bytes (4 x ${sizeOf<Int32>()})');
}items[1]: -200000 items[3]: -400000 sizeOf<Row>(): 16 bytes (4 x 4)
external void operator []=(int index, int value)Stores a Raya value in this array at index.
This extension method must be invoked on a receiver of type Array<T> where T is a compile-time constant type.
import 'raya:ffi';
final class Row extends Struct {
@Array(4)
external Array<Int32> items;
}
void main() {
final row = Struct.create<Row>();
row.items[0] = 100000;
row.items[1] = -400000;
// Int32 holds about +-2.1e9, so 3e9 wraps.
row.items[2] = 3000000000;
print('items[0] = ${row.items[0]}');
print('items[1] = ${row.items[1]}');
print('items[2] = ${row.items[2]} (stored 3000000000)');
print('items[3] = ${row.items[3]} (never set)');
}items[0] = 100000 items[1] = -400000 items[2] = -1294967296 (stored 3000000000) items[3] = 0 (never set)
Int64Array
extension Int64Array on Array<Int64>
Properties
external Int64List get elementsA list view of the bytes of this array.
Has the same length and elements (as accessed using the index operator) as this array, and writes to either the list or this arrary are visible in both.
Operators
external int operator [](int index)Loads a Raya value from this array at index.
This extension method must be invoked on a receiver of type Array<T> where T is a compile-time constant type.
import 'raya:ffi';
final class Row extends Struct {
@Array(4)
external Array<Int64> items;
}
void main() {
final row = Struct.create<Row>();
const values = [1099511627776, -1099511627776, 7, -7];
for (var i = 0; i < 4; i++) {
row.items[i] = values[i];
}
print('items[1]: ${row.items[1]}');
print('items[3]: ${row.items[3]}');
print('sizeOf<Row>(): ${sizeOf<Row>()} bytes (4 x ${sizeOf<Int64>()})');
}items[1]: -1099511627776 items[3]: -7 sizeOf<Row>(): 32 bytes (4 x 8)
external void operator []=(int index, int value)Stores a Raya value in this array at index.
This extension method must be invoked on a receiver of type Array<T> where T is a compile-time constant type.
import 'raya:ffi';
final class Row extends Struct {
@Array(4)
external Array<Int64> items;
}
void main() {
final row = Struct.create<Row>();
row.items[0] = 1099511627776;
row.items[1] = -7;
// Int64 is the full int range: the minimum survives.
row.items[2] = -9223372036854775808;
print('items[0] = ${row.items[0]}');
print('items[1] = ${row.items[1]}');
print('items[2] = ${row.items[2]} (stored -9223372036854775808)');
print('items[3] = ${row.items[3]} (never set)');
}items[0] = 1099511627776 items[1] = -7 items[2] = -9223372036854775808 (stored -9223372036854775808) items[3] = 0 (never set)
Uint8Array
extension Uint8Array on Array<Uint8>
Properties
external Uint8List get elementsA list view of the bytes of this array.
Has the same length and elements (as accessed using the index operator) as this array, and writes to either the list or this arrary are visible in both.
Operators
external int operator [](int index)Loads a Raya value from this array at index.
This extension method must be invoked on a receiver of type Array<T> where T is a compile-time constant type.
import 'raya:ffi';
final class Row extends Struct {
@Array(4)
external Array<Uint8> items;
}
void main() {
final row = Struct.create<Row>();
const values = [10, 20, 250, 255];
for (var i = 0; i < 4; i++) {
row.items[i] = values[i];
}
print('items[1]: ${row.items[1]}');
print('items[3]: ${row.items[3]}');
print('sizeOf<Row>(): ${sizeOf<Row>()} bytes (4 x ${sizeOf<Uint8>()})');
}items[1]: 20 items[3]: 255 sizeOf<Row>(): 4 bytes (4 x 1)
external void operator []=(int index, int value)Stores a Raya value in this array at index.
This extension method must be invoked on a receiver of type Array<T> where T is a compile-time constant type.
import 'raya:ffi';
final class Row extends Struct {
@Array(4)
external Array<Uint8> items;
}
void main() {
final row = Struct.create<Row>();
row.items[0] = 10;
row.items[1] = 255;
// Uint8 holds 0..255, so 300 wraps.
row.items[2] = 300;
print('items[0] = ${row.items[0]}');
print('items[1] = ${row.items[1]}');
print('items[2] = ${row.items[2]} (stored 300)');
print('items[3] = ${row.items[3]} (never set)');
}items[0] = 10 items[1] = 255 items[2] = 44 (stored 300) items[3] = 0 (never set)
Uint16Array
extension Uint16Array on Array<Uint16>
Properties
external Uint16List get elementsA list view of the bytes of this array.
Has the same length and elements (as accessed using the index operator) as this array, and writes to either the list or this arrary are visible in both.
Operators
external int operator [](int index)Loads a Raya value from this array at index.
This extension method must be invoked on a receiver of type Array<T> where T is a compile-time constant type.
import 'raya:ffi';
final class Row extends Struct {
@Array(4)
external Array<Uint16> items;
}
void main() {
final row = Struct.create<Row>();
const values = [1000, 2000, 65000, 65535];
for (var i = 0; i < 4; i++) {
row.items[i] = values[i];
}
print('items[1]: ${row.items[1]}');
print('items[3]: ${row.items[3]}');
print('sizeOf<Row>(): ${sizeOf<Row>()} bytes (4 x ${sizeOf<Uint16>()})');
}items[1]: 2000 items[3]: 65535 sizeOf<Row>(): 8 bytes (4 x 2)
external void operator []=(int index, int value)Stores a Raya value in this array at index.
This extension method must be invoked on a receiver of type Array<T> where T is a compile-time constant type.
import 'raya:ffi';
final class Row extends Struct {
@Array(4)
external Array<Uint16> items;
}
void main() {
final row = Struct.create<Row>();
row.items[0] = 1000;
row.items[1] = 65535;
// Uint16 holds 0..65535, so 70000 wraps.
row.items[2] = 70000;
print('items[0] = ${row.items[0]}');
print('items[1] = ${row.items[1]}');
print('items[2] = ${row.items[2]} (stored 70000)');
print('items[3] = ${row.items[3]} (never set)');
}items[0] = 1000 items[1] = 65535 items[2] = 4464 (stored 70000) items[3] = 0 (never set)
Uint32Array
extension Uint32Array on Array<Uint32>
Properties
external Uint32List get elementsA list view of the bytes of this array.
Has the same length and elements (as accessed using the index operator) as this array, and writes to either the list or this arrary are visible in both.
Operators
external int operator [](int index)Loads a Raya value from this array at index.
This extension method must be invoked on a receiver of type Array<T> where T is a compile-time constant type.
import 'raya:ffi';
final class Row extends Struct {
@Array(4)
external Array<Uint32> items;
}
void main() {
final row = Struct.create<Row>();
const values = [1, 1000000, 4000000000, 4294967295];
for (var i = 0; i < 4; i++) {
row.items[i] = values[i];
}
print('items[1]: ${row.items[1]}');
print('items[3]: ${row.items[3]}');
print('sizeOf<Row>(): ${sizeOf<Row>()} bytes (4 x ${sizeOf<Uint32>()})');
}items[1]: 1000000 items[3]: 4294967295 sizeOf<Row>(): 16 bytes (4 x 4)
external void operator []=(int index, int value)Stores a Raya value in this array at index.
This extension method must be invoked on a receiver of type Array<T> where T is a compile-time constant type.
import 'raya:ffi';
final class Row extends Struct {
@Array(4)
external Array<Uint32> items;
}
void main() {
final row = Struct.create<Row>();
row.items[0] = 1;
row.items[1] = 4294967295;
// Uint32 holds 0..4294967295, so -1 reads as the maximum.
row.items[2] = -1;
print('items[0] = ${row.items[0]}');
print('items[1] = ${row.items[1]}');
print('items[2] = ${row.items[2]} (stored -1)');
print('items[3] = ${row.items[3]} (never set)');
}items[0] = 1 items[1] = 4294967295 items[2] = 4294967295 (stored -1) items[3] = 0 (never set)
Uint64Array
extension Uint64Array on Array<Uint64>
Properties
external Uint64List get elementsA list view of the bytes of this array.
Has the same length and elements (as accessed using the index operator) as this array, and writes to either the list or this arrary are visible in both.
Operators
external int operator [](int index)Loads a Raya value from this array at index.
This extension method must be invoked on a receiver of type Array<T> where T is a compile-time constant type.
import 'raya:ffi';
final class Row extends Struct {
@Array(4)
external Array<Uint64> items;
}
void main() {
final row = Struct.create<Row>();
const values = [1, 1099511627776, 4611686018427387904, 12345];
for (var i = 0; i < 4; i++) {
row.items[i] = values[i];
}
print('items[1]: ${row.items[1]}');
print('items[3]: ${row.items[3]}');
print('sizeOf<Row>(): ${sizeOf<Row>()} bytes (4 x ${sizeOf<Uint64>()})');
}items[1]: 1099511627776 items[3]: 12345 sizeOf<Row>(): 32 bytes (4 x 8)
external void operator []=(int index, int value)Stores a Raya value in this array at index.
This extension method must be invoked on a receiver of type Array<T> where T is a compile-time constant type.
import 'raya:ffi';
final class Row extends Struct {
@Array(4)
external Array<Uint64> items;
}
void main() {
final row = Struct.create<Row>();
row.items[0] = 1;
row.items[1] = 12345;
// Uint64 shares int's 64 bits: -1 is stored as all ones.
row.items[2] = -1;
print('items[0] = ${row.items[0]}');
print('items[1] = ${row.items[1]}');
print('items[2] = ${row.items[2]} (stored -1)');
print('items[3] = ${row.items[3]} (never set)');
}items[0] = 1 items[1] = 12345 items[2] = -1 (stored -1) items[3] = 0 (never set)
FloatArray
extension FloatArray on Array<Float>
Properties
external Float32List get elementsA list view of the bytes of this array.
Has the same length and elements (as accessed using the index operator) as this array, and writes to either the list or this arrary are visible in both.
Operators
external double operator [](int index)Loads a Raya value from this array at index.
This extension method must be invoked on a receiver of type Array<T> where T is a compile-time constant type.
import 'raya:ffi';
final class Row extends Struct {
@Array(4)
external Array<Float> items;
}
void main() {
final row = Struct.create<Row>();
const values = [0.5, 1.25, -2.0, 3.75];
for (var i = 0; i < 4; i++) {
row.items[i] = values[i];
}
print('items[1]: ${row.items[1]}');
print('items[3]: ${row.items[3]}');
print('sizeOf<Row>(): ${sizeOf<Row>()} bytes (4 x ${sizeOf<Float>()})');
}items[1]: 1.25 items[3]: 3.75 sizeOf<Row>(): 16 bytes (4 x 4)
external void operator []=(int index, double value)Stores a Raya value in this array at index.
This extension method must be invoked on a receiver of type Array<T> where T is a compile-time constant type.
import 'raya:ffi';
final class Row extends Struct {
@Array(4)
external Array<Float> items;
}
void main() {
final row = Struct.create<Row>();
row.items[0] = 0.5;
row.items[1] = 3.75;
// Float is 32-bit, so 0.1 comes back rounded.
row.items[2] = 0.1;
print('items[0] = ${row.items[0]}');
print('items[1] = ${row.items[1]}');
print('items[2] = ${row.items[2]} (stored 0.1)');
print('items[3] = ${row.items[3]} (never set)');
}items[0] = 0.5 items[1] = 3.75 items[2] = 0.10000000149011612 (stored 0.1) items[3] = 0.0 (never set)
DoubleArray
extension DoubleArray on Array<Double>
Properties
external Float64List get elementsA list view of the bytes of this array.
Has the same length and elements (as accessed using the index operator) as this array, and writes to either the list or this arrary are visible in both.
Operators
external double operator [](int index)Loads a Raya value from this array at index.
This extension method must be invoked on a receiver of type Array<T> where T is a compile-time constant type.
import 'raya:ffi';
final class Row extends Struct {
@Array(4)
external Array<Double> items;
}
void main() {
final row = Struct.create<Row>();
const values = [0.5, 1.25, -2.0, 3.75];
for (var i = 0; i < 4; i++) {
row.items[i] = values[i];
}
print('items[1]: ${row.items[1]}');
print('items[3]: ${row.items[3]}');
print('sizeOf<Row>(): ${sizeOf<Row>()} bytes (4 x ${sizeOf<Double>()})');
}items[1]: 1.25 items[3]: 3.75 sizeOf<Row>(): 32 bytes (4 x 8)
external void operator []=(int index, double value)Stores a Raya value in this array at index.
This extension method must be invoked on a receiver of type Array<T> where T is a compile-time constant type.
import 'raya:ffi';
final class Row extends Struct {
@Array(4)
external Array<Double> items;
}
void main() {
final row = Struct.create<Row>();
row.items[0] = 0.5;
row.items[1] = 3.75;
// Double is 64-bit, so 0.1 comes back exactly as written.
row.items[2] = 0.1;
print('items[0] = ${row.items[0]}');
print('items[1] = ${row.items[1]}');
print('items[2] = ${row.items[2]} (stored 0.1)');
print('items[3] = ${row.items[3]} (never set)');
}items[0] = 0.5 items[1] = 3.75 items[2] = 0.1 (stored 0.1) items[3] = 0.0 (never set)
BoolArray
extension BoolArray on Array<Bool>
Properties
external List<bool> get elementsA list view of the bytes of this array.
Has the same length and elements (as accessed using the index operator) as this array, and writes to either the list or this arrary are visible in both.
Operators
external bool operator [](int index)Loads a Raya value from this array at index.
This extension method must be invoked on a receiver of type Array<T> where T is a compile-time constant type.
import 'raya:ffi';
final class Row extends Struct {
@Array(4)
external Array<Bool> items;
}
void main() {
final row = Struct.create<Row>();
const values = [true, false, true, true];
for (var i = 0; i < 4; i++) {
row.items[i] = values[i];
}
print('items[1]: ${row.items[1]}');
print('items[3]: ${row.items[3]}');
print('sizeOf<Row>(): ${sizeOf<Row>()} bytes (4 x ${sizeOf<Bool>()})');
}items[1]: false items[3]: true sizeOf<Row>(): 4 bytes (4 x 1)
external void operator []=(int index, bool value)Stores a Raya value in this array at index.
This extension method must be invoked on a receiver of type Array<T> where T is a compile-time constant type.
import 'raya:ffi';
final class Row extends Struct {
@Array(4)
external Array<Bool> items;
}
void main() {
final row = Struct.create<Row>();
row.items[0] = true;
row.items[1] = true;
// Bool stores one byte per flag.
row.items[2] = true;
print('items[0] = ${row.items[0]}');
print('items[1] = ${row.items[1]}');
print('items[2] = ${row.items[2]} (stored true)');
print('items[3] = ${row.items[3]} (never set)');
}items[0] = true items[1] = true items[2] = true (stored true) items[3] = false (never set)
Int8ListAddress
extension Int8ListAddress on Int8List
Properties
external Pointer<Int8> get addressThe memory address of the underlying data.
An expression of the form expression.address denoting this address can only occurr as an entire argument expression in the invocation of a leaf Native external function.
Example:
@Native<Void Function(Pointer<Int8>)>(isLeaf: true)
external void myFunction(Pointer<Int8> pointer);
void main() {
final list = Int8List(10);
myFunction(list.address);
}
The expression before .address is evaluated like the left-hand-side of an assignment, to something that gives access to the storage behind the expression, which can be used both for reading and writing. The .address then gives a native pointer to that storage.
The .address is evaluated just before calling into native code when invoking a leaf Native external function. This ensures the Raya garbage collector will not move the object that the address points in to.
Int16ListAddress
extension Int16ListAddress on Int16List
Properties
external Pointer<Int16> get addressThe memory address of the underlying data.
An expression of the form expression.address denoting this address can only occurr as an entire argument expression in the invocation of a leaf Native external function.
Example:
@Native<Void Function(Pointer<Int16>)>(isLeaf: true)
external void myFunction(Pointer<Int16> pointer);
void main() {
final list = Int16List(10);
myFunction(list.address);
}
The expression before .address is evaluated like the left-hand-side of an assignment, to something that gives access to the storage behind the expression, which can be used both for reading and writing. The .address then gives a native pointer to that storage.
The .address is evaluated just before calling into native code when invoking a leaf Native external function. This ensures the Raya garbage collector will not move the object that the address points in to.
Int32ListAddress
extension Int32ListAddress on Int32List
Properties
external Pointer<Int32> get addressThe memory address of the underlying data.
An expression of the form expression.address denoting this address can only occurr as an entire argument expression in the invocation of a leaf Native external function.
Example:
@Native<Void Function(Pointer<Int32>)>(isLeaf: true)
external void myFunction(Pointer<Int32> pointer);
void main() {
final list = Int32List(10);
myFunction(list.address);
}
The expression before .address is evaluated like the left-hand-side of an assignment, to something that gives access to the storage behind the expression, which can be used both for reading and writing. The .address then gives a native pointer to that storage.
The .address is evaluated just before calling into native code when invoking a leaf Native external function. This ensures the Raya garbage collector will not move the object that the address points in to.
Int64ListAddress
extension Int64ListAddress on Int64List
Properties
external Pointer<Int64> get addressThe memory address of the underlying data.
An expression of the form expression.address denoting this address can only occurr as an entire argument expression in the invocation of a leaf Native external function.
Example:
@Native<Void Function(Pointer<Int64>)>(isLeaf: true)
external void myFunction(Pointer<Int64> pointer);
void main() {
final list = Int64List(10);
myFunction(list.address);
}
The expression before .address is evaluated like the left-hand-side of an assignment, to something that gives access to the storage behind the expression, which can be used both for reading and writing. The .address then gives a native pointer to that storage.
The .address is evaluated just before calling into native code when invoking a leaf Native external function. This ensures the Raya garbage collector will not move the object that the address points in to.
Uint8ListAddress
extension Uint8ListAddress on Uint8List
Properties
external Pointer<Uint8> get addressThe memory address of the underlying data.
An expression of the form expression.address denoting this address can only occurr as an entire argument expression in the invocation of a leaf Native external function.
Example:
@Native<Void Function(Pointer<Uint8>)>(isLeaf: true)
external void myFunction(Pointer<Uint8> pointer);
void main() {
final list = Uint8List(10);
myFunction(list.address);
}
The expression before .address is evaluated like the left-hand-side of an assignment, to something that gives access to the storage behind the expression, which can be used both for reading and writing. The .address then gives a native pointer to that storage.
The .address is evaluated just before calling into native code when invoking a leaf Native external function. This ensures the Raya garbage collector will not move the object that the address points in to.
Uint16ListAddress
extension Uint16ListAddress on Uint16List
Properties
external Pointer<Uint16> get addressThe memory address of the underlying data.
An expression of the form expression.address denoting this address can only occurr as an entire argument expression in the invocation of a leaf Native external function.
Example:
@Native<Void Function(Pointer<Uint16>)>(isLeaf: true)
external void myFunction(Pointer<Uint16> pointer);
void main() {
final list = Uint16List(10);
myFunction(list.address);
}
The expression before .address is evaluated like the left-hand-side of an assignment, to something that gives access to the storage behind the expression, which can be used both for reading and writing. The .address then gives a native pointer to that storage.
The .address is evaluated just before calling into native code when invoking a leaf Native external function. This ensures the Raya garbage collector will not move the object that the address points in to.
Uint32ListAddress
extension Uint32ListAddress on Uint32List
Properties
external Pointer<Uint32> get addressThe memory address of the underlying data.
An expression of the form expression.address denoting this address can only occurr as an entire argument expression in the invocation of a leaf Native external function.
Example:
@Native<Void Function(Pointer<Uint32>)>(isLeaf: true)
external void myFunction(Pointer<Uint32> pointer);
void main() {
final list = Uint32List(10);
myFunction(list.address);
}
The expression before .address is evaluated like the left-hand-side of an assignment, to something that gives access to the storage behind the expression, which can be used both for reading and writing. The .address then gives a native pointer to that storage.
The .address is evaluated just before calling into native code when invoking a leaf Native external function. This ensures the Raya garbage collector will not move the object that the address points in to.
Uint64ListAddress
extension Uint64ListAddress on Uint64List
Properties
external Pointer<Uint64> get addressThe memory address of the underlying data.
An expression of the form expression.address denoting this address can only occurr as an entire argument expression in the invocation of a leaf Native external function.
Example:
@Native<Void Function(Pointer<Uint64>)>(isLeaf: true)
external void myFunction(Pointer<Uint64> pointer);
void main() {
final list = Uint64List(10);
myFunction(list.address);
}
The expression before .address is evaluated like the left-hand-side of an assignment, to something that gives access to the storage behind the expression, which can be used both for reading and writing. The .address then gives a native pointer to that storage.
The .address is evaluated just before calling into native code when invoking a leaf Native external function. This ensures the Raya garbage collector will not move the object that the address points in to.
Float32ListAddress
extension Float32ListAddress on Float32List
Properties
external Pointer<Float> get addressThe memory address of the underlying data.
An expression of the form expression.address denoting this address can only occurr as an entire argument expression in the invocation of a leaf Native external function.
Example:
@Native<Void Function(Pointer<Float>)>(isLeaf: true)
external void myFunction(Pointer<Float> pointer);
void main() {
final list = Float32List(10);
myFunction(list.address);
}
The expression before .address is evaluated like the left-hand-side of an assignment, to something that gives access to the storage behind the expression, which can be used both for reading and writing. The .address then gives a native pointer to that storage.
The .address is evaluated just before calling into native code when invoking a leaf Native external function. This ensures the Raya garbage collector will not move the object that the address points in to.
Float64ListAddress
extension Float64ListAddress on Float64List
Properties
external Pointer<Double> get addressThe memory address of the underlying data.
An expression of the form expression.address denoting this address can only occurr as an entire argument expression in the invocation of a leaf Native external function.
Example:
@Native<Void Function(Pointer<Double>)>(isLeaf: true)
external void myFunction(Pointer<Double> pointer);
void main() {
final list = Float64List(10);
myFunction(list.address);
}
The expression before .address is evaluated like the left-hand-side of an assignment, to something that gives access to the storage behind the expression, which can be used both for reading and writing. The .address then gives a native pointer to that storage.
The .address is evaluated just before calling into native code when invoking a leaf Native external function. This ensures the Raya garbage collector will not move the object that the address points in to.
PointerPointer
extension PointerPointer<T extends NativeType> on Pointer<Pointer<T>>
Properties
external Pointer<T> get valueThe pointer at address.
A Pointer is unboxed before being stored (as if by .address), and the pointer is boxed (as if by Pointer.fromAddress) when loaded.
On 32-bit platforms the address must be 4-byte aligned, and on 64-bit platforms the address must be 8-byte aligned.
external void set value(Pointer<T> value)import 'raya:ffi';
// A tiny allocator over the C library's malloc and free.
final class Libc implements Allocator {
static final _lib = DynamicLibrary.process();
static final _malloc = _lib.lookupFunction<Pointer<Void> Function(IntPtr), Pointer<Void> Function(int)>('malloc');
static final _free = _lib.lookupFunction<Void Function(Pointer<Void>), void Function(Pointer<Void>)>('free');
@override
Pointer<T> allocate<T extends NativeType>(int byteCount, {int? alignment}) => _malloc(byteCount).cast();
@override
void free(Pointer pointer) => _free(pointer.cast());
}
final libc = Libc();
void main() {
final a = libc<Int32>()..value = 1, b = libc<Int32>()..value = 2;
final slot = libc<Pointer<Int32>>();
slot.value = a;
print('*slot -> ${slot.value.value}');
slot.value = b;
print('after slot.value = b: ${slot.value.value}');
[a, b, slot].forEach(libc.free);
}*slot -> 1 after slot.value = b: 2
Methods
external Pointer<Pointer<T>> elementAt(int index)Pointer arithmetic (takes element size into account).
import 'raya:ffi';
// A tiny allocator over the C library's malloc and free.
final class Libc implements Allocator {
static final _lib = DynamicLibrary.process();
static final _malloc = _lib.lookupFunction<Pointer<Void> Function(IntPtr), Pointer<Void> Function(int)>('malloc');
static final _free = _lib.lookupFunction<Void Function(Pointer<Void>), void Function(Pointer<Void>)>('free');
@override
Pointer<T> allocate<T extends NativeType>(int byteCount, {int? alignment}) => _malloc(byteCount).cast();
@override
void free(Pointer pointer) => _free(pointer.cast());
}
final libc = Libc();
void main() {
final table = libc<Pointer<Int32>>(2);
final x = libc<Int32>()..value = 10, y = libc<Int32>()..value = 20;
table[0] = x;
table[1] = y;
print('elementAt(1).value.value: ${table.elementAt(1).value.value}');
[x, y, table].forEach(libc.free);
}elementAt(1).value.value: 20
Operators
external Pointer<T> operator [](int index)Load a Raya value from this location offset by index.
A Pointer is unboxed before being stored (as if by .address), and the pointer is boxed (as if by Pointer.fromAddress) when loaded.
On 32-bit platforms the address must be 4-byte aligned, and on 64-bit platforms the address must be 8-byte aligned.
import 'raya:ffi';
// A tiny allocator over the C library's malloc and free.
final class Libc implements Allocator {
static final _lib = DynamicLibrary.process();
static final _malloc = _lib.lookupFunction<Pointer<Void> Function(IntPtr), Pointer<Void> Function(int)>('malloc');
static final _free = _lib.lookupFunction<Void Function(Pointer<Void>), void Function(Pointer<Void>)>('free');
@override
Pointer<T> allocate<T extends NativeType>(int byteCount, {int? alignment}) => _malloc(byteCount).cast();
@override
void free(Pointer pointer) => _free(pointer.cast());
}
final libc = Libc();
void main() {
final words = libc<Pointer<Uint8>>(2);
final hi = libc<Uint8>(3), yo = libc<Uint8>(3);
[104, 105, 0].asMap().forEach((i, c) => hi[i] = c);
[121, 111, 0].asMap().forEach((i, c) => yo[i] = c);
words[0] = hi;
words[1] = yo;
String cstr(Pointer<Uint8> s) => String.fromCharCodes(s.asTypedList(2));
print('words[0]: ${cstr(words[0])}, words[1]: ${cstr(words[1])}');
[hi, yo, words].forEach(libc.free);
}words[0]: hi, words[1]: yo
external void operator []=(int index, Pointer<T> value)Store a Raya value into this location offset by index.
A Pointer is unboxed before being stored (as if by .address), and the pointer is boxed (as if by Pointer.fromAddress) when loaded.
On 32-bit platforms the address must be 4-byte aligned, and on 64-bit platforms the address must be 8-byte aligned.
import 'raya:ffi';
// A tiny allocator over the C library's malloc and free.
final class Libc implements Allocator {
static final _lib = DynamicLibrary.process();
static final _malloc = _lib.lookupFunction<Pointer<Void> Function(IntPtr), Pointer<Void> Function(int)>('malloc');
static final _free = _lib.lookupFunction<Void Function(Pointer<Void>), void Function(Pointer<Void>)>('free');
@override
Pointer<T> allocate<T extends NativeType>(int byteCount, {int? alignment}) => _malloc(byteCount).cast();
@override
void free(Pointer pointer) => _free(pointer.cast());
}
final libc = Libc();
void main() {
final slots = libc<Pointer<Int8>>(3);
final value = libc<Int8>()..value = 5;
for (var i = 0; i < 3; i++) {
slots[i] = i == 1 ? value : nullptr;
}
print('slots null?: ${[for (var i = 0; i < 3; i++) slots[i] == nullptr]}');
print('slots[1].value: ${slots[1].value}');
[value, slots].forEach(libc.free);
}slots null?: [true, false, true] slots[1].value: 5
external Pointer<Pointer<T>> operator +(int offset)A pointer to the offsetth [Pointer<T>] after this one.
Returns a pointer to the [Pointer<T>] whose address is offset times the size of Pointer<T> after the address of this pointer. That is (this + offset).address == this.address + offset * sizeOf<Pointer<T>>.
Also (this + offset).value is equivalent to this[offset], and similarly for setting.
import 'raya:ffi';
// A tiny allocator over the C library's malloc and free.
final class Libc implements Allocator {
static final _lib = DynamicLibrary.process();
static final _malloc = _lib.lookupFunction<Pointer<Void> Function(IntPtr), Pointer<Void> Function(int)>('malloc');
static final _free = _lib.lookupFunction<Void Function(Pointer<Void>), void Function(Pointer<Void>)>('free');
@override
Pointer<T> allocate<T extends NativeType>(int byteCount, {int? alignment}) => _malloc(byteCount).cast();
@override
void free(Pointer pointer) => _free(pointer.cast());
}
final libc = Libc();
void main() {
final arr = libc<Pointer<Void>>(4);
final third = arr + 2;
print('arr + 2 is ${third.address - arr.address} bytes on (2 pointers)');
libc.free(arr);
}arr + 2 is 16 bytes on (2 pointers)
external Pointer<Pointer<T>> operator -(int offset)A pointer to the offsetth [Pointer<T>] before this one.
Equivalent to this + (-offset).
Returns a pointer to the [Pointer<T>] whose address is offset times the size of Pointer<T> before the address of this pointer. That is, (this - offset).address == this.address - offset * sizeOf<Pointer<T>>.
Also, (this - offset).value is equivalent to this[-offset], and similarly for setting,
import 'raya:ffi';
// A tiny allocator over the C library's malloc and free.
final class Libc implements Allocator {
static final _lib = DynamicLibrary.process();
static final _malloc = _lib.lookupFunction<Pointer<Void> Function(IntPtr), Pointer<Void> Function(int)>('malloc');
static final _free = _lib.lookupFunction<Void Function(Pointer<Void>), void Function(Pointer<Void>)>('free');
@override
Pointer<T> allocate<T extends NativeType>(int byteCount, {int? alignment}) => _malloc(byteCount).cast();
@override
void free(Pointer pointer) => _free(pointer.cast());
}
final libc = Libc();
void main() {
final arr = libc<Pointer<Void>>(4);
final end = arr + 4;
print('(end - 1) == arr + 3: ${(end - 1) == arr + 3}');
print('step back: ${end.address - (end - 1).address} bytes');
libc.free(arr);
}(end - 1) == arr + 3: true step back: 8 bytes
StructPointer
extension StructPointer<T extends Struct> on Pointer<T>
Properties
external T get refA Raya view of the struct referenced by this pointer.
Reading ref creates a reference accessing the fields of this struct backed by native memory at address. The address must be aligned according to the struct alignment rules of the platform.
Assigning to ref copies contents of the struct into the native memory starting at address.
This extension method must be invoked on a receiver of type Pointer<T> where T is a compile-time constant type.
external set ref(T value)import 'raya:ffi';
// A tiny allocator over the C library's malloc and free.
final class Libc implements Allocator {
static final _lib = DynamicLibrary.process();
static final _malloc = _lib.lookupFunction<Pointer<Void> Function(IntPtr), Pointer<Void> Function(int)>('malloc');
static final _free = _lib.lookupFunction<Void Function(Pointer<Void>), void Function(Pointer<Void>)>('free');
@override
Pointer<T> allocate<T extends NativeType>(int byteCount, {int? alignment}) => _malloc(byteCount).cast();
@override
void free(Pointer pointer) => _free(pointer.cast());
}
final libc = Libc();
final class Point extends Struct {
@Int32()
external int x, y;
}
void main() {
final p = libc<Point>();
final tmp = Struct.create<Point>()
..x = 3
..y = 4;
p.ref = tmp; // copies the struct into native memory
tmp.x = 99;
print('native copy: (${p.ref.x}, ${p.ref.y}), temp now x=${tmp.x}');
libc.free(p);
}native copy: (3, 4), temp now x=99
Methods
external T refWithFinalizer(Pointer<NativeFinalizerFunction> finalizer, {Pointer<Void>? token})A Raya view of the struct referenced by this pointer.
Creates a reference accessing the fields of this struct backed by native memory at address. The address must be aligned according to the struct alignment rules of the platform.
Attaches finalizer to the backing store of the struct. If provided, token will be passed to finalizer, otherwise the pointer (this) itself will be passed. The pointer (this) must not be used anymore if the struct is not guaranteed to be kept alive. Prefer doing any native calls with the pointer before calling refWithFinalizer.
This extension method must be invoked on a receiver of type Pointer<T> where T is a compile-time constant type.
import 'raya:ffi';
final class Point extends Struct {
@Double()
external double x, y;
}
final lib = DynamicLibrary.process();
final malloc = lib.lookupFunction<Pointer<Void> Function(Size), Pointer<Void> Function(int)>('malloc');
final free = lib.lookup<NativeFinalizerFunction>('free');
void main() {
// The memory is freed by C free once the returned struct is unreachable.
final pt = malloc(sizeOf<Point>()).cast<Point>().refWithFinalizer(free);
pt
..x = 1.5
..y = -2;
print('point: (${pt.x}, ${pt.y}); no explicit free needed');
}point: (1.5, -2.0); no explicit free needed
external Pointer<T> elementAt(int index)Pointer arithmetic (takes element size into account)
import 'raya:ffi';
// A tiny allocator over the C library's malloc and free.
final class Libc implements Allocator {
static final _lib = DynamicLibrary.process();
static final _malloc = _lib.lookupFunction<Pointer<Void> Function(IntPtr), Pointer<Void> Function(int)>('malloc');
static final _free = _lib.lookupFunction<Void Function(Pointer<Void>), void Function(Pointer<Void>)>('free');
@override
Pointer<T> allocate<T extends NativeType>(int byteCount, {int? alignment}) => _malloc(byteCount).cast();
@override
void free(Pointer pointer) => _free(pointer.cast());
}
final libc = Libc();
final class Pair extends Struct {
@Int16()
external int a, b;
}
void main() {
final p = libc<Pair>(3);
for (var i = 0; i < 3; i++) {
p.elementAt(i).ref
..a = i
..b = -i;
}
final last = p.elementAt(2).ref;
print('elementAt(2): (${last.a}, ${last.b}), stride ${p.elementAt(1).address - p.address} bytes');
libc.free(p);
}elementAt(2): (2, -2), stride 4 bytes
Operators
external T operator [](int index)Creates a reference to access the fields of this struct backed by native memory at address + sizeOf<T> * index.
The address must be aligned according to the struct alignment rules of the platform.
This extension method must be invoked on a receiver of type Pointer<T> where T is a compile-time constant type.
import 'raya:ffi';
// A tiny allocator over the C library's malloc and free.
final class Libc implements Allocator {
static final _lib = DynamicLibrary.process();
static final _malloc = _lib.lookupFunction<Pointer<Void> Function(IntPtr), Pointer<Void> Function(int)>('malloc');
static final _free = _lib.lookupFunction<Void Function(Pointer<Void>), void Function(Pointer<Void>)>('free');
@override
Pointer<T> allocate<T extends NativeType>(int byteCount, {int? alignment}) => _malloc(byteCount).cast();
@override
void free(Pointer pointer) => _free(pointer.cast());
}
final libc = Libc();
final class Item extends Struct {
@Int32()
external int id;
@Float()
external double price;
}
void main() {
final items = libc<Item>(2);
items[0]
..id = 1
..price = 2.5;
items[1]
..id = 2
..price = 4.0;
print([for (var i = 0; i < 2; i++) 'id ${items[i].id}: ${items[i].price}'].join(', '));
libc.free(items);
}id 1: 2.5, id 2: 4.0
external void operator []=(int index, T value)Copies the value struct into native memory, starting at address * sizeOf<T> * index.
This extension method must be invoked on a receiver of type Pointer<T> where T is a compile-time constant type.
import 'raya:ffi';
// A tiny allocator over the C library's malloc and free.
final class Libc implements Allocator {
static final _lib = DynamicLibrary.process();
static final _malloc = _lib.lookupFunction<Pointer<Void> Function(IntPtr), Pointer<Void> Function(int)>('malloc');
static final _free = _lib.lookupFunction<Void Function(Pointer<Void>), void Function(Pointer<Void>)>('free');
@override
Pointer<T> allocate<T extends NativeType>(int byteCount, {int? alignment}) => _malloc(byteCount).cast();
@override
void free(Pointer pointer) => _free(pointer.cast());
}
final libc = Libc();
final class V2 extends Struct {
@Int32()
external int x, y;
}
void main() {
final vs = libc<V2>(2);
final v = Struct.create<V2>()
..x = 7
..y = 8;
vs[0] = v;
vs[1] = v;
vs[1].y = 0;
print('vs[0]: (${vs[0].x}, ${vs[0].y}), vs[1]: (${vs[1].x}, ${vs[1].y})');
libc.free(vs);
}vs[0]: (7, 8), vs[1]: (7, 0)
external Pointer<T> operator +(int offset)A pointer to the offsetth T after this one.
Returns a pointer to the T whose address is offset times the size of T after the address of this pointer. That is (this + offset).address == this.address + offset * sizeOf<T>.
Also (this + offset).value is equivalent to this[offset], and similarly for setting.
import 'raya:ffi';
// A tiny allocator over the C library's malloc and free.
final class Libc implements Allocator {
static final _lib = DynamicLibrary.process();
static final _malloc = _lib.lookupFunction<Pointer<Void> Function(IntPtr), Pointer<Void> Function(int)>('malloc');
static final _free = _lib.lookupFunction<Void Function(Pointer<Void>), void Function(Pointer<Void>)>('free');
@override
Pointer<T> allocate<T extends NativeType>(int byteCount, {int? alignment}) => _malloc(byteCount).cast();
@override
void free(Pointer pointer) => _free(pointer.cast());
}
final libc = Libc();
final class Rec extends Struct {
@Int64()
external int key;
@Int32()
external int val;
}
void main() {
final r = libc<Rec>(3);
(r + 2).ref.val = 42;
print('(r + 2).ref.val: ${r[2].val}');
print('struct size with padding: ${(r + 1).address - r.address} bytes');
libc.free(r);
}(r + 2).ref.val: 42 struct size with padding: 16 bytes
external Pointer<T> operator -(int offset)A pointer to the offsetth T before this one.
Equivalent to this + (-offset).
Returns a pointer to the T whose address is offset times the size of T before the address of this pointer. That is, (this - offset).address == this.address - offset * sizeOf<T>.
Also, (this - offset).value is equivalent to this[-offset], and similarly for setting,
import 'raya:ffi';
// A tiny allocator over the C library's malloc and free.
final class Libc implements Allocator {
static final _lib = DynamicLibrary.process();
static final _malloc = _lib.lookupFunction<Pointer<Void> Function(IntPtr), Pointer<Void> Function(int)>('malloc');
static final _free = _lib.lookupFunction<Void Function(Pointer<Void>), void Function(Pointer<Void>)>('free');
@override
Pointer<T> allocate<T extends NativeType>(int byteCount, {int? alignment}) => _malloc(byteCount).cast();
@override
void free(Pointer pointer) => _free(pointer.cast());
}
final libc = Libc();
final class Cell extends Struct {
@Int32()
external int v;
}
void main() {
final c = libc<Cell>(3);
for (var i = 0; i < 3; i++) c[i].v = i * 10;
final end = c + 3;
print('(end - 1).ref.v: ${(end - 1).ref.v}');
libc.free(c);
}(end - 1).ref.v: 20
UnionPointer
extension UnionPointer<T extends Union> on Pointer<T>
Properties
external T get refA Raya view of the union referenced by this pointer.
Reading ref creates a reference accessing the fields of this union backed by native memory at address. The address must be aligned according to the union alignment rules of the platform.
Assigning to ref copies contents of the union into the native memory starting at address.
This extension method must be invoked on a receiver of type Pointer<T> where T is a compile-time constant type.
external set ref(T value)import 'raya:ffi';
// A tiny allocator over the C library's malloc and free.
final class Libc implements Allocator {
static final _lib = DynamicLibrary.process();
static final _malloc = _lib.lookupFunction<Pointer<Void> Function(IntPtr), Pointer<Void> Function(int)>('malloc');
static final _free = _lib.lookupFunction<Void Function(Pointer<Void>), void Function(Pointer<Void>)>('free');
@override
Pointer<T> allocate<T extends NativeType>(int byteCount, {int? alignment}) => _malloc(byteCount).cast();
@override
void free(Pointer pointer) => _free(pointer.cast());
}
final libc = Libc();
final class Num extends Union {
@Int32()
external int i;
@Float()
external double f;
}
void main() {
final p = libc<Num>();
p.ref = Union.create<Num>()..f = 1.0; // copied into native memory
print('float 1.0 seen as int bits: 0x${p.ref.i.toRadixString(16)}');
libc.free(p);
}float 1.0 seen as int bits: 0x3f800000
Methods
external T refWithFinalizer(Pointer<NativeFinalizerFunction> finalizer, {Pointer<Void>? token})A Raya view of the union referenced by this pointer.
Creates a reference accessing the fields of this union backed by native memory at address. The address must be aligned according to the union alignment rules of the platform.
Attaches finalizer to the backing store of the union. If provided, token will be passed to finalizer, otherwise the pointer (this) itself will be passed. The pointer (this) must not be used anymore if the union is not guaranteed to be kept alive. Prefer doing any native calls with the pointer before calling refWithFinalizer.
This extension method must be invoked on a receiver of type Pointer<T> where T is a compile-time constant type.
import 'raya:ffi';
final class Word extends Union {
@Uint32()
external int whole;
@Array(4)
external Array<Uint8> bytes;
}
final lib = DynamicLibrary.process();
final malloc = lib.lookupFunction<Pointer<Void> Function(Size), Pointer<Void> Function(int)>('malloc');
final free = lib.lookup<NativeFinalizerFunction>('free');
void main() {
final w = malloc(sizeOf<Word>()).cast<Word>().refWithFinalizer(free);
w.whole = 0xAABBCCDD;
print('low byte: 0x${w.bytes[0].toRadixString(16)}, high byte: 0x${w.bytes[3].toRadixString(16)}');
}low byte: 0xdd, high byte: 0xaa
external Pointer<T> elementAt(int index)Pointer arithmetic (takes element size into account).
import 'raya:ffi';
// A tiny allocator over the C library's malloc and free.
final class Libc implements Allocator {
static final _lib = DynamicLibrary.process();
static final _malloc = _lib.lookupFunction<Pointer<Void> Function(IntPtr), Pointer<Void> Function(int)>('malloc');
static final _free = _lib.lookupFunction<Void Function(Pointer<Void>), void Function(Pointer<Void>)>('free');
@override
Pointer<T> allocate<T extends NativeType>(int byteCount, {int? alignment}) => _malloc(byteCount).cast();
@override
void free(Pointer pointer) => _free(pointer.cast());
}
final libc = Libc();
final class IntOrFloat extends Union {
@Int32()
external int i;
@Float()
external double f;
}
void main() {
final u = libc<IntOrFloat>(2);
u.elementAt(0).ref.f = 2.0;
u.elementAt(1).ref.i = 7;
print('u[0] as int bits: 0x${u.elementAt(0).ref.i.toRadixString(16)}, u[1].i: ${u.elementAt(1).ref.i}');
libc.free(u);
}u[0] as int bits: 0x40000000, u[1].i: 7
Operators
external T operator [](int index)Creates a reference to access the fields of this union backed by native memory at address + sizeOf<T> * index.
The address must be aligned according to the union alignment rules of the platform.
This extension method must be invoked on a receiver of type Pointer<T> where T is a compile-time constant type.
import 'raya:ffi';
// A tiny allocator over the C library's malloc and free.
final class Libc implements Allocator {
static final _lib = DynamicLibrary.process();
static final _malloc = _lib.lookupFunction<Pointer<Void> Function(IntPtr), Pointer<Void> Function(int)>('malloc');
static final _free = _lib.lookupFunction<Void Function(Pointer<Void>), void Function(Pointer<Void>)>('free');
@override
Pointer<T> allocate<T extends NativeType>(int byteCount, {int? alignment}) => _malloc(byteCount).cast();
@override
void free(Pointer pointer) => _free(pointer.cast());
}
final libc = Libc();
final class Tag extends Union {
@Uint16()
external int code;
@Array(2)
external Array<Uint8> raw;
}
void main() {
final t = libc<Tag>(2);
t[0].code = 0x0102;
t[1].code = 0xFFEE;
print('t[0].raw: [${t[0].raw[0]}, ${t[0].raw[1]}], t[1].raw[0]: ${t[1].raw[0]}');
libc.free(t);
}t[0].raw: [2, 1], t[1].raw[0]: 238
external void operator []=(int index, T value)Copies the value union into native memory, starting at address * sizeOf<T> * index.
This extension method must be invoked on a receiver of type Pointer<T> where T is a compile-time constant type.
import 'raya:ffi';
// A tiny allocator over the C library's malloc and free.
final class Libc implements Allocator {
static final _lib = DynamicLibrary.process();
static final _malloc = _lib.lookupFunction<Pointer<Void> Function(IntPtr), Pointer<Void> Function(int)>('malloc');
static final _free = _lib.lookupFunction<Void Function(Pointer<Void>), void Function(Pointer<Void>)>('free');
@override
Pointer<T> allocate<T extends NativeType>(int byteCount, {int? alignment}) => _malloc(byteCount).cast();
@override
void free(Pointer pointer) => _free(pointer.cast());
}
final libc = Libc();
final class Val extends Union {
@Int64()
external int n;
@Double()
external double d;
}
void main() {
final vals = libc<Val>(2);
vals[1] = Union.create<Val>()..d = 0.5;
print('vals[1].d: ${vals[1].d}');
libc.free(vals);
}vals[1].d: 0.5
external Pointer<T> operator +(int offset)A pointer to the offsetth T after this one.
Returns a pointer to the T whose address is offset times the size of T after the address of this pointer. That is (this + offset).address == this.address + offset * sizeOf<T>.
Also (this + offset).value is equivalent to this[offset], and similarly for setting.
import 'raya:ffi';
// A tiny allocator over the C library's malloc and free.
final class Libc implements Allocator {
static final _lib = DynamicLibrary.process();
static final _malloc = _lib.lookupFunction<Pointer<Void> Function(IntPtr), Pointer<Void> Function(int)>('malloc');
static final _free = _lib.lookupFunction<Void Function(Pointer<Void>), void Function(Pointer<Void>)>('free');
@override
Pointer<T> allocate<T extends NativeType>(int byteCount, {int? alignment}) => _malloc(byteCount).cast();
@override
void free(Pointer pointer) => _free(pointer.cast());
}
final libc = Libc();
final class U extends Union {
@Int8()
external int small;
@Int64()
external int big;
}
void main() {
final u = libc<U>(3);
(u + 1).ref.big = -1;
print('(u + 1).ref.small: ${(u + 1).ref.small}');
print('union size = largest member: ${(u + 1).address - u.address} bytes');
libc.free(u);
}(u + 1).ref.small: -1 union size = largest member: 8 bytes
external Pointer<T> operator -(int offset)A pointer to the offsetth T before this one.
Equivalent to this + (-offset).
Returns a pointer to the T whose address is offset times the size of T before the address of this pointer. That is, (this - offset).address == this.address - offset * sizeOf<T>.
Also, (this - offset).value is equivalent to this[-offset], and similarly for setting,
import 'raya:ffi';
// A tiny allocator over the C library's malloc and free.
final class Libc implements Allocator {
static final _lib = DynamicLibrary.process();
static final _malloc = _lib.lookupFunction<Pointer<Void> Function(IntPtr), Pointer<Void> Function(int)>('malloc');
static final _free = _lib.lookupFunction<Void Function(Pointer<Void>), void Function(Pointer<Void>)>('free');
@override
Pointer<T> allocate<T extends NativeType>(int byteCount, {int? alignment}) => _malloc(byteCount).cast();
@override
void free(Pointer pointer) => _free(pointer.cast());
}
final libc = Libc();
final class U extends Union {
@Int32()
external int i;
@Float()
external double f;
}
void main() {
final u = libc<U>(2);
final end = u + 2;
(end - 1).ref.i = 99;
print('u[1].i via end - 1: ${u[1].i}');
libc.free(u);
}u[1].i via end - 1: 99
AbiSpecificIntegerPointer
extension AbiSpecificIntegerPointer<T extends AbiSpecificInteger> on Pointer<T>
Extension on Pointer specialized for the type argument AbiSpecificInteger.
Properties
external void set value(int value)import 'raya:ffi';
// A tiny allocator over the C library's malloc and free.
final class Libc implements Allocator {
static final _lib = DynamicLibrary.process();
static final _malloc = _lib.lookupFunction<Pointer<Void> Function(IntPtr), Pointer<Void> Function(int)>('malloc');
static final _free = _lib.lookupFunction<Void Function(Pointer<Void>), void Function(Pointer<Void>)>('free');
@override
Pointer<T> allocate<T extends NativeType>(int byteCount, {int? alignment}) => _malloc(byteCount).cast();
@override
void free(Pointer pointer) => _free(pointer.cast());
}
final libc = Libc();
void main() {
// Long is 64-bit on macOS and Linux, 32-bit on Windows.
final p = libc<Long>();
p.value = 1 << 40;
print('Long holds 2^40 here: ${p.value == 1 << 40} (sizeOf<Long>() = ${sizeOf<Long>()})');
libc.free(p);
}Long holds 2^40 here: true (sizeOf<Long>() = 8)
Methods
external Pointer<T> elementAt(int index)Pointer arithmetic (takes element size into account).
import 'raya:ffi';
// A tiny allocator over the C library's malloc and free.
final class Libc implements Allocator {
static final _lib = DynamicLibrary.process();
static final _malloc = _lib.lookupFunction<Pointer<Void> Function(IntPtr), Pointer<Void> Function(int)>('malloc');
static final _free = _lib.lookupFunction<Void Function(Pointer<Void>), void Function(Pointer<Void>)>('free');
@override
Pointer<T> allocate<T extends NativeType>(int byteCount, {int? alignment}) => _malloc(byteCount).cast();
@override
void free(Pointer pointer) => _free(pointer.cast());
}
final libc = Libc();
void main() {
final p = libc<Size>(3);
for (var i = 0; i < 3; i++) p.elementAt(i).value = i * 1000;
print('elementAt(2).value: ${p.elementAt(2).value}');
libc.free(p);
}elementAt(2).value: 2000
Operators
external int operator [](int index)The integer at address + sizeOf<T> * index.
import 'raya:ffi';
// A tiny allocator over the C library's malloc and free.
final class Libc implements Allocator {
static final _lib = DynamicLibrary.process();
static final _malloc = _lib.lookupFunction<Pointer<Void> Function(IntPtr), Pointer<Void> Function(int)>('malloc');
static final _free = _lib.lookupFunction<Void Function(Pointer<Void>), void Function(Pointer<Void>)>('free');
@override
Pointer<T> allocate<T extends NativeType>(int byteCount, {int? alignment}) => _malloc(byteCount).cast();
@override
void free(Pointer pointer) => _free(pointer.cast());
}
final libc = Libc();
void main() {
final p = libc<UnsignedShort>(2);
p[0] = 65535;
p[1] = 65536; // wraps to 0
print('p[0]: ${p[0]}, p[1]: ${p[1]}');
libc.free(p);
}p[0]: 65535, p[1]: 0
external void operator []=(int index, int value)The integer at address + sizeOf<T> * index.
import 'raya:ffi';
// A tiny allocator over the C library's malloc and free.
final class Libc implements Allocator {
static final _lib = DynamicLibrary.process();
static final _malloc = _lib.lookupFunction<Pointer<Void> Function(IntPtr), Pointer<Void> Function(int)>('malloc');
static final _free = _lib.lookupFunction<Void Function(Pointer<Void>), void Function(Pointer<Void>)>('free');
@override
Pointer<T> allocate<T extends NativeType>(int byteCount, {int? alignment}) => _malloc(byteCount).cast();
@override
void free(Pointer pointer) => _free(pointer.cast());
}
final libc = Libc();
void main() {
final p = libc<Short>(3);
for (var i = 0; i < 3; i++) p[i] = 30000 + i * 3000;
print('Short wraps: ${[p[0], p[1], p[2]]}');
libc.free(p);
}Short wraps: [30000, -32536, -29536]
external Pointer<T> operator +(int offset)A pointer to the offsetth T after this one.
Returns a pointer to the T whose address is offset times the size of T after the address of this pointer. That is (this + offset).address == this.address + offset * sizeOf<T>.
Also (this + offset).value is equivalent to this[offset], and similarly for setting.
import 'raya:ffi';
// A tiny allocator over the C library's malloc and free.
final class Libc implements Allocator {
static final _lib = DynamicLibrary.process();
static final _malloc = _lib.lookupFunction<Pointer<Void> Function(IntPtr), Pointer<Void> Function(int)>('malloc');
static final _free = _lib.lookupFunction<Void Function(Pointer<Void>), void Function(Pointer<Void>)>('free');
@override
Pointer<T> allocate<T extends NativeType>(int byteCount, {int? alignment}) => _malloc(byteCount).cast();
@override
void free(Pointer pointer) => _free(pointer.cast());
}
final libc = Libc();
void main() {
final p = libc<Int>(4);
(p + 3).value = -5;
print('(p + 3).value: ${p[3]}, step ${(p + 1).address - p.address} bytes');
libc.free(p);
}(p + 3).value: -5, step 4 bytes
external Pointer<T> operator -(int offset)A pointer to the offsetth T before this one.
Equivalent to this + (-offset).
Returns a pointer to the T whose address is offset times the size of T before the address of this pointer. That is, (this - offset).address == this.address - offset * sizeOf<T>.
Also, (this - offset).value is equivalent to this[-offset], and similarly for setting,
import 'raya:ffi';
// A tiny allocator over the C library's malloc and free.
final class Libc implements Allocator {
static final _lib = DynamicLibrary.process();
static final _malloc = _lib.lookupFunction<Pointer<Void> Function(IntPtr), Pointer<Void> Function(int)>('malloc');
static final _free = _lib.lookupFunction<Void Function(Pointer<Void>), void Function(Pointer<Void>)>('free');
@override
Pointer<T> allocate<T extends NativeType>(int byteCount, {int? alignment}) => _malloc(byteCount).cast();
@override
void free(Pointer pointer) => _free(pointer.cast());
}
final libc = Libc();
void main() {
final p = libc<UnsignedInt>(2);
final end = p + 2;
(end - 1).value = 4294967295;
print('last UnsignedInt: ${p[1]}');
libc.free(p);
}last UnsignedInt: 4294967295
PointerArray
extension PointerArray<T extends NativeType> on Array<Pointer<T>>
Properties
external List<Pointer<T>> get elementsA list view of the bytes of this array.
Has the same length and elements (as accessed using the index operator) as this array, and writes to either the list or this arrary are visible in both.
Operators
external Pointer<T> operator [](int index)Loads a Raya value from this array at index.
This extension method must be invoked on a receiver of type Array<T> where T is a compile-time constant type.
import 'raya:ffi';
// A tiny allocator over the C library's malloc and free.
final class Libc implements Allocator {
static final _lib = DynamicLibrary.process();
static final _malloc = _lib.lookupFunction<Pointer<Void> Function(IntPtr), Pointer<Void> Function(int)>('malloc');
static final _free = _lib.lookupFunction<Void Function(Pointer<Void>), void Function(Pointer<Void>)>('free');
@override
Pointer<T> allocate<T extends NativeType>(int byteCount, {int? alignment}) => _malloc(byteCount).cast();
@override
void free(Pointer pointer) => _free(pointer.cast());
}
final libc = Libc();
final class Slots extends Struct {
@Array(2)
external Array<Pointer<Int32>> ptrs;
}
void main() {
final a = libc<Int32>()..value = 11;
final s = Struct.create<Slots>();
s.ptrs[0] = a;
s.ptrs[1] = nullptr;
print('ptrs[0].value: ${s.ptrs[0].value}, ptrs[1] is null: ${s.ptrs[1] == nullptr}');
libc.free(a);
}ptrs[0].value: 11, ptrs[1] is null: true
external void operator []=(int index, Pointer<T> value)Stores a Raya value in this array at index.
This extension method must be invoked on a receiver of type Array<T> where T is a compile-time constant type.
import 'raya:ffi';
// A tiny allocator over the C library's malloc and free.
final class Libc implements Allocator {
static final _lib = DynamicLibrary.process();
static final _malloc = _lib.lookupFunction<Pointer<Void> Function(IntPtr), Pointer<Void> Function(int)>('malloc');
static final _free = _lib.lookupFunction<Void Function(Pointer<Void>), void Function(Pointer<Void>)>('free');
@override
Pointer<T> allocate<T extends NativeType>(int byteCount, {int? alignment}) => _malloc(byteCount).cast();
@override
void free(Pointer pointer) => _free(pointer.cast());
}
final libc = Libc();
final class Argv extends Struct {
@Array(3)
external Array<Pointer<Uint8>> args;
}
void main() {
final av = Struct.create<Argv>();
final bufs = [for (final c in [97, 98]) libc<Uint8>()..value = c];
av.args[0] = bufs[0];
av.args[1] = bufs[1];
av.args[2] = nullptr; // terminator, like C's argv
print('first chars: ${String.fromCharCodes([av.args[0].value, av.args[1].value])}');
bufs.forEach(libc.free);
}first chars: ab
StructArray
extension StructArray<T extends Struct> on Array<T>
Properties
external List<T> get elementsA list view of the bytes of this array.
Has the same length and elements (as accessed using the index operator) as this array.
Operators
external T operator [](int index)This extension method must be invoked on a receiver of type Pointer<T> where T is a compile-time constant type.
import 'raya:ffi';
final class Pt extends Struct {
@Int16()
external int x, y;
}
final class Triangle extends Struct {
@Array(3)
external Array<Pt> corners;
}
void main() {
final t = Struct.create<Triangle>();
for (var i = 0; i < 3; i++) {
t.corners[i]
..x = i
..y = i * 2;
}
print('corner 2: (${t.corners[2].x}, ${t.corners[2].y}), sizeOf ${sizeOf<Triangle>()}');
}corner 2: (2, 4), sizeOf 12
UnionArray
extension UnionArray<T extends Union> on Array<T>
Properties
external List<T> get elementsA list view of the bytes of this array.
Has the same length and elements (as accessed using the index operator) as this array.
Operators
external T operator [](int index)This extension method must be invoked on a receiver of type Pointer<T> where T is a compile-time constant type.
import 'raya:ffi';
final class Slot extends Union {
@Int32()
external int i;
@Float()
external double f;
}
final class Regs extends Struct {
@Array(2)
external Array<Slot> r;
}
void main() {
final regs = Struct.create<Regs>();
regs.r[0].i = 5;
regs.r[1].f = -0.0;
print('r[0].i: ${regs.r[0].i}, r[1] bits: 0x${regs.r[1].i.toUnsigned(32).toRadixString(16)}');
}r[0].i: 5, r[1] bits: 0x80000000
ArrayArray
extension ArrayArray<T extends NativeType> on Array<Array<T>>
Properties
external List<Array<T>> get elementsA list view of the bytes of this array.
Has the same length and elements (as accessed using the index operator) as this array, and writes to either the list or this arrary are visible in both.
Operators
external Array<T> operator [](int index)import 'raya:ffi';
final class M2 extends Struct {
@Array.multi([2, 2])
external Array<Array<Float>> m;
}
void main() {
final a = Struct.create<M2>();
a.m[0][0] = 1;
a.m[0][1] = 2;
a.m[1][0] = 3;
a.m[1][1] = 4;
final det = a.m[0][0] * a.m[1][1] - a.m[0][1] * a.m[1][0];
print('row 1: [${a.m[1][0]}, ${a.m[1][1]}], det = $det');
}row 1: [3.0, 4.0], det = -2.0
external void operator []=(int index, Array<T> value)import 'raya:ffi';
final class Grid extends Struct {
@Array.multi([2, 3])
external Array<Array<Uint8>> g;
}
void main() {
final src = Struct.create<Grid>(), dst = Struct.create<Grid>();
for (var c = 0; c < 3; c++) src.g[0][c] = c + 1;
dst.g[1] = src.g[0]; // copies a whole row
print('dst row 1: ${[for (var c = 0; c < 3; c++) dst.g[1][c]]}');
}dst row 1: [1, 2, 3]
AbiSpecificIntegerArray
extension AbiSpecificIntegerArray<T extends AbiSpecificInteger> on Array<T>
Bounds checking indexing methods on Arrays of AbiSpecificInteger.
Properties
external List<int> get elementsA list view of the bytes of this array.
Has the same length and elements (as accessed using the index operator) as this array, and writes to either the list or this arrary are visible in both.
Operators
external int operator [](int index)Loads a Raya value from this array at index.
This extension method must be invoked on a receiver of type Array<T> where T is a compile-time constant type.
import 'raya:ffi';
final class Sizes extends Struct {
@Array(3)
external Array<Size> s;
}
void main() {
final x = Struct.create<Sizes>();
x.s[0] = 1;
x.s[1] = 1 << 33;
print('s[1] == 2^33: ${x.s[1] == 1 << 33}, sizeOf<Sizes>(): ${sizeOf<Sizes>()}');
}s[1] == 2^33: true, sizeOf<Sizes>(): 24
external void operator []=(int index, int value)Stores a Raya value in this array at index.
This extension method must be invoked on a receiver of type Array<T> where T is a compile-time constant type.
import 'raya:ffi';
final class Chars extends Struct {
@Array(4)
external Array<UnsignedChar> c;
}
void main() {
final s = Struct.create<Chars>();
final word = 'Raya'.codeUnits;
for (var i = 0; i < 4; i++) s.c[i] = word[i];
print('chars: ${String.fromCharCodes([for (var i = 0; i < 4; i++) s.c[i]])}');
}chars: Raya
ArrayAddress
extension ArrayAddress<T extends NativeType> on Array<T>
Properties
external Pointer<T> get addressThe memory address of the underlying data.
An expression of the form expression.address denoting this address can only occurr as an entire argument expression in the invocation of a leaf Native external function.
Example:
@Native<Void Function(Pointer<Int8>)>(isLeaf: true)
external void myFunction(Pointer<Int8> pointer);
final class MyStruct extends Struct {
@Array(10)
external Array<Int8> array;
}
void main() {
final array = Struct.create<MyStruct>().array;
myFunction(array.address);
}
The expression before .address is evaluated like the left-hand-side of an assignment, to something that gives access to the storage behind the expression, which can be used both for reading and writing. The .address then gives a native pointer to that storage.
The .address is evaluated just before calling into native code when invoking a leaf Native external function. This ensures the Raya garbage collector will not move the object that the address points in to.
StructAddress
extension StructAddress<T extends Struct> on T
Properties
external Pointer<T> get addressThe memory address of the underlying data.
An expression of the form expression.address denoting this address can only occurr as an entire argument expression in the invocation of a leaf Native external function.
Example:
@Native<Void Function(Pointer<MyStruct>)>(isLeaf: true)
external void myFunction(Pointer<MyStruct> pointer);
final class MyStruct extends Struct {
@Int8()
external int x;
}
void main() {
final myStruct = Struct.create<MyStruct>();
myFunction(myStruct.address);
}
The expression before .address is evaluated like the left-hand-side of an assignment, to something that gives access to the storage behind the expression, which can be used both for reading and writing. The .address then gives a native pointer to that storage.
The .address is evaluated just before calling into native code when invoking a leaf Native external function. This ensures the Raya garbage collector will not move the object that the address points in to.
UnionAddress
extension UnionAddress<T extends Union> on T
Properties
external Pointer<T> get addressThe memory address of the underlying data.
An expression of the form expression.address denoting this address can only occurr as an entire argument expression in the invocation of a leaf Native external function.
Example:
@Native<Void Function(Pointer<MyUnion>)>(isLeaf: true)
external void myFunction(Pointer<MyUnion> pointer);
final class MyUnion extends Union {
@Int8()
external int x;
}
void main() {
final myUnion = Union.create<MyUnion>();
myFunction(myUnion.address);
}
The expression before .address is evaluated like the left-hand-side of an assignment, to something that gives access to the storage behind the expression, which can be used both for reading and writing. The .address then gives a native pointer to that storage.
The .address is evaluated just before calling into native code when invoking a leaf Native external function. This ensures the Raya garbage collector will not move the object that the address points in to.
IntAddress
extension IntAddress on int
Properties
external Pointer<Never> get addressThe memory address of the underlying data.
An expression of the form expression.address denoting this address can only occurr as an entire argument expression in the invocation of a leaf Native external function.
Can only be used on fields of Struct subtypes, fields of Union subtypes, Array elements, or TypedData elements. In other words, the number whose address is being accessed must itself be acccessed through a Struct, Union, Array, or TypedData.
Example:
@Native<Void Function(Pointer<Int8>)>(isLeaf: true)
external void myFunction(Pointer<Int8> pointer);
final class MyStruct extends Struct {
@Int8()
external int x;
@Int8()
external int y;
@Array(10)
external Array<Int8> array;
}
void main() {
final myStruct = Struct.create<MyStruct>();
myFunction(myStruct.y.address);
myFunction(myStruct.array[5].address);
final list = Int8List(10);
myFunction(list[5].address);
}
The expression before .address is evaluated like the left-hand-side of an assignment, to something that gives access to the storage behind the expression, which can be used both for reading and writing. The .address then gives a native pointer to that storage.
The .address is evaluated just before calling into native code when invoking a leaf Native external function. This ensures the Raya garbage collector will not move the object that the address points in to.
DoubleAddress
extension DoubleAddress on double
Properties
external Pointer<Never> get addressThe memory address of the underlying data.
An expression of the form expression.address denoting this address can only occurr as an entire argument expression in the invocation of a leaf Native external function.
Can only be used on fields of Struct subtypes, fields of Union subtypes, Array elements, or TypedData elements. In other words, the number whose address is being accessed must itself be acccessed through a Struct, Union, Array, or TypedData.
Example:
@Native<Void Function(Pointer<Float>)>(isLeaf: true)
external void myFunction(Pointer<Float> pointer);
final class MyStruct extends Struct {
@Float()
external double x;
@Float()
external double y;
@Array(10)
external Array<Float> array;
}
void main() {
final myStruct = Struct.create<MyStruct>();
myFunction(myStruct.y.address);
myFunction(myStruct.array[5].address);
final list = Float32List(10);
myFunction(list[5].address);
}
The expression before .address is evaluated like the left-hand-side of an assignment, to something that gives access to the storage behind the expression, which can be used both for reading and writing. The .address then gives a native pointer to that storage.
The .address is evaluated just before calling into native code when invoking a leaf Native external function. This ensures the Raya garbage collector will not move the object that the address points in to.
BoolAddress
extension BoolAddress on bool
Properties
external Pointer<Never> get addressThe memory address of the underlying data.
An expression of the form expression.address denoting this address can only occurr as an entire argument expression in the invocation of a leaf Native external function.
Can only be used on fields of Struct subtypes, fields of Union subtypes, or Array elements. In other words, the boolean whose address is being accessed must itself be acccessed through a Struct, Union or Array.
Example:
@Native<Void Function(Pointer<Int8>)>(isLeaf: true)
external void myFunction(Pointer<Int8> pointer);
final class MyStruct extends Struct {
@Bool()
external bool x;
@Bool()
external bool y;
@Array(10)
external Array<Bool> array;
}
void main() {
final myStruct = Struct.create<MyStruct>();
myFunction(myStruct.y.address);
myFunction(myStruct.array[5].address);
}
The expression before .address is evaluated like the left-hand-side of an assignment, to something that gives access to the storage behind the expression, which can be used both for reading and writing. The .address then gives a native pointer to that storage.
The .address is evaluated just before calling into native code when invoking a leaf Native external function. This ensures the Raya garbage collector will not move the object that the address points in to.
NativePort
extension NativePort on SendPort
Extension to retrieve the native Raya_Port from a SendPort.
Properties
external int get nativePortThe native port of this SendPort.
The returned native port can for example be used by C code to post messages to the connected ReceivePort via Raya_PostCObject - see raya_native_api.h.
Only the send ports from the platform classes ReceivePort and RawReceivePort are supported. User-defined implementations of SendPort are not supported.
Dart_CObject
final class Dart_CObject extends Opaque
Opaque, not exposing it's members.
NativeApi
abstract final class NativeApi
Utilities for accessing the Raya VM API from Raya code or from C code via raya_api_dl.h.
Static
external static int get majorVersionOn breaking changes the major version is increased.
The versioning covers the API surface in raya_api_dl.h.
external static int get minorVersionOn backwards compatible changes the minor version is increased.
The versioning covers the API surface in raya_api_dl.h.
external static Pointer< NativeFunction<Int8 Function(Int64, Pointer<Dart_CObject>)> > get postCObjectA function pointer to bool Raya_PostCObject(Raya_Port port_id, Dart_CObject* message) in raya_native_api.h.
external static Pointer< NativeFunction< Int64 Function(Pointer<Uint8>, Pointer<NativeFunction<Dart_NativeMessageHandler>>, Int8) > > get newNativePortA function pointer to
Raya_Port Raya_NewNativePort(const char* name,
Dart_NativeMessageHandler handler,
bool handle_concurrently)
In raya_native_api.h.
external static Pointer<NativeFunction<Int8 Function(Int64)>> get closeNativePortA function pointer to bool Raya_CloseNativePort(Raya_Port native_port_id) in raya_native_api.h.
external static Pointer<Void> get initializeApiDLDataPass this to Raya_InitializeApiDL in your native code to enable using the symbols in raya_api_dl.h.
Native
final class Native<T>
Annotation binding an external declaration to its native implementation.
Can only be applied to external declarations of static and top-level functions and variables.
A Native-annotated external function is implemented by native code. The implementation is found in the native library denoted by assetId. Similarly, a Native-annotated external variable is implemented by reading from or writing to native memory.
The compiler and/or runtime provides a binding from assetId to native library, which depends on the target platform. The compiler/runtime can then resolve/lookup symbols (identifiers) against the native library, to find a native function or a native global variable, and bind an external Raya function or variable declaration to that native declaration. By default, the runtime expects a native symbol with the same name as the annotated function or variable in Raya. This can be overridden with the symbol parameter on the annotation.
When used on a function, T must be a function type that represents the native function's parameter and return types. The parameter and return types must be subtypes of NativeType.
When used on a variable, T must be a compatible native type. For example, an int field can be annotated with Int32.
If the type argument T is omitted in the @Native annotation, it is inferred from the static type of the declaration, which must meet the following constraints:
For function or method declarations:
- The return type must be one of the following:
- The parameter types must be subtypes of compound types or
Pointer
For variable declarations, the type can be any of the following:
For native global variables that cannot be reassigned, a final variable in Raya or a getter can be used to prevent modifications to the native field.
Example:
@Native<Int64 Function(Int64, Int64)>()
external int sum(int a, int b);
@Native()
external void free(Pointer p);
@Native<Int64>()
external int aGlobalInt;
@Native()
external final Pointer<Char> aGlobalString;
Calling a @Native function, as well as reading or writing to a @Native variable, will try to resolve the symbol in (in the order):
- The provided or default
assetId, - The native resolver set with
Raya_SetFfiNativeResolverinraya_api.h, and - The current process.
At least one of those three must provide a binding for the symbol, otherwise the method call or the variable access fails.
NOTE: This is an experimental feature and may change in the future.
Constructors
const Native({this.assetId, this.isLeaf = false, this.symbol})import 'raya:ffi';
// Bind a C function directly; the symbol is looked up in the running process.
@Native<Int32 Function(Int32)>(symbol: 'abs')
external int cAbs(int x);
@Native<Double Function(Double)>(symbol: 'sqrt', isLeaf: true)
external double cSqrt(double x);
void main() {
print('abs(-7) = ${cAbs(-7)}');
print('sqrt(2) = ${cSqrt(2)}');
}abs(-7) = 7 sqrt(2) = 1.4142135623730951
Static
external static Pointer<T> addressOf<T extends NativeType>(@DartRepresentationOf('T') Object native)The native address of the implementation of native.
When calling this function, the argument for native must be an expression denoting a variable or function declaration which is annotated with Native. For a variable declaration, the type T must be the same native type as the type argument to that @Native annotation. For a function declaration, the type T must be NativeFunction<F> where F was the type argument to that @Native annotation.
For example, for a native C library exposing a function:
#include <stdint.h>
int64_t sum(int64_t a, int64_t b) { return a + b; }
The following code binds sum to a Raya function declaration, and extracts the address of the native sum implementation:
import 'raya:ffi';
typedef NativeAdd = Int64 Function(Int64, Int64);
@Native<NativeAdd>()
external int sum(int a, int b);
void main() {
Pointer<NativeFunction<NativeAdd>> addressSum = Native.addressOf(sum);
}
Similarly, for a native C library exposing a global variable:
const char* myString;
The following code binds myString to a top-level variable in Raya, and extracts the address of the underlying native field:
import 'raya:ffi';
@Native()
external Pointer<Char> myString;
void main() {
// This pointer points to the memory location where the loader has
// placed the `myString` global itself. To get the string value, read
// the myString field directly.
Pointer<Pointer<Char>> addressMyString = Native.addressOf(myString);
}import 'raya:ffi';
@Native<Int32 Function(Int32)>(symbol: 'abs')
external int cAbs(int x);
void main() {
final Pointer<NativeFunction<Int32 Function(Int32)>> p = Native.addressOf(cAbs);
print('address is non-null: ${p != nullptr}');
print('call through the pointer: ${p.asFunction<int Function(int)>()(-12)}');
}address is non-null: true call through the pointer: 12
Properties
final String? symbolThe native symbol to be resolved, if not using the default.
If not specified, the default symbol used for native function lookup is the annotated function's name.
Example:
@Native<Int64 Function(Int64, Int64)>()
external int sum(int a, int b);
Example 2:
@Native<Int64 Function(Int64, Int64)>(symbol: 'sum')
external int sum(int a, int b);
The above two examples are equivalent.
Prefer omitting the symbol when possible.
final String? assetIdThe ID of the asset in which symbol is resolved, if not using the default.
If no asset name is specified, the default is to use an asset ID specified using an DefaultAsset annotation on the current library's library declaration, and if there is no DefaultAsset annotation on the current library, the library's URI (as a string) is used instead.
Example (file package:a/a.ray):
@Native<Int64 Function(Int64, Int64)>()
external int sum(int a, int b);
Example 2 (file package:a/a.ray):
@DefaultAsset('package:a/a.ray')
library a;
import 'raya:ffi';
@Native<Int64 Function(Int64, Int64)>()
external int sum(int a, int b);
Example 3 (file package:a/a.ray):
@Native<Int64 Function(Int64, Int64)>(assetId: 'package:a/a.ray')
external int sum(int a, int b);
The above three examples are all equivalent.
Prefer using the library URI as an asset name over specifying it. Prefer using an DefaultAsset on the library declaration over specifying the asset name in a Native annotation.
final bool isLeafWhether the function is a leaf function.
Leaf functions are small, short-running, non-blocking functions which are not allowed to call back into Raya or use any Raya VM APIs. Leaf functions are invoked bypassing some of the heavier parts of the standard Raya-to-Native calling sequence which reduces the invocation overhead, making leaf calls faster than non-leaf calls. However, this implies that a thread executing a leaf function can't cooperate with the Raya runtime. A long running or blocking leaf function will delay any operation which requires synchronization between all threads associated with an isolate group until after the leaf function returns. For example, if one isolate in a group is trying to perform a GC and a second isolate is blocked in a leaf call, then the first isolate will have to pause and wait until this leaf call returns.
This value has no meaning for native fields.
DefaultAsset
final class DefaultAsset
Annotation specifying the default asset ID for the current library.
The annotation applies only to library declarations.
The compiler and/or runtime provides a binding from asset ID to native library, which depends on the target platform and architecture. The compiler/runtime can resolve identifiers (symbols) against the native library, looking up native function implementations which are then used as the implementation of external Raya function declarations.
If used as annotation on a library declaration, all Native-annotated external functions in this library will use the specified asset id for native function resolution (unless overridden by Native.assetId).
If no DefaultAsset annotation is provided, the current library's URI is the default asset ID for Native-annotated external functions.
Example (file package:a/a.ray):
@Native<Int64 Function(Int64, Int64)>()
external int sum(int a, int b);
Example 2 (file package:a/a.ray):
@DefaultAsset('package:a/a.ray')
library a;
import 'raya:ffi';
@Native<Int64 Function(Int64, Int64)>()
external int sum(int a, int b);
The above two examples are equivalent.
Prefer using the library URI as asset name when possible.
NOTE: This is an experimental feature and may change in the future.
Constructors
const DefaultAsset(this.id)@DefaultAsset('package:my_app/libc')
library;
import 'raya:ffi';
// Every @Native in this library uses the asset above unless it names its own.
// With no asset of that name bundled, lookup falls back to the process.
@Native<Int32 Function(Int32)>(symbol: 'abs')
external int cAbs(int x);
void main() {
print('abs(-3) = ${cAbs(-3)}');
}abs(-3) = 3
Properties
Abi
class Abi
An application binary interface (ABI).
An ABI defines the memory layout of data and the function call protocol for native code. It is usually defined by the an operating system for each architecture that operating system runs on.
The Raya VM can run on a variety of operating systems and architectures. Supported ABIs are represented by Abi objects. See values for all the supported ABIs.
Constructors
external factory Abi.current()The ABI the Raya VM is currently running on.
import 'raya:ffi';
void main() {
final abi = Abi.current();
print('one of the supported ABIs: ${Abi.values.contains(abi)}');
print('supported ABIs: ${Abi.values.length}');
}one of the supported ABIs: true supported ABIs: 22
Static
static const androidArm = _androidArmThe application binary interface for Android on the Arm architecture.
static const androidArm64 = _androidArm64The application binary interface for Android on the Arm64 architecture.
static const androidIA32 = _androidIA32The application binary interface for Android on the IA32 architecture.
static const androidX64 = _androidX64The application binary interface for Android on the X64 architecture.
static const androidRiscv64 = _androidRiscv64The application binary interface for Android on 64-bit RISC-V.
static const fuchsiaArm64 = _fuchsiaArm64The application binary interface for Fuchsia on the Arm64 architecture.
static const fuchsiaX64 = _fuchsiaX64The application binary interface for Fuchsia on the X64 architecture.
static const fuchsiaRiscv64 = _fuchsiaRiscv64The application binary interface for Fuchsia on the Riscv64 architecture.
static const iosArm = _iosArmThe application binary interface for iOS on the Arm architecture.
static const iosArm64 = _iosArm64The application binary interface for iOS on the Arm64 architecture.
static const iosX64 = _iosX64The application binary interface for iOS on the X64 architecture.
static const linuxArm = _linuxArmThe application binary interface for Linux on the Arm architecture.
Does not distinguish between hard and soft fp. Currently, no uses of Abi require this distinction.
static const linuxArm64 = _linuxArm64The application binary interface for linux on the Arm64 architecture.
static const linuxIA32 = _linuxIA32The application binary interface for linux on the IA32 architecture.
static const linuxX64 = _linuxX64The application binary interface for linux on the X64 architecture.
static const linuxRiscv32 = _linuxRiscv32The application binary interface for linux on 32-bit RISC-V.
static const linuxRiscv64 = _linuxRiscv64The application binary interface for linux on 64-bit RISC-V.
static const macosArm64 = _macosArm64The application binary interface for MacOS on the Arm64 architecture.
static const macosX64 = _macosX64The application binary interface for MacOS on the X64 architecture.
static const windowsArm64 = _windowsArm64The application binary interface for Windows on the Arm64 architecture.
static const windowsIA32 = _windowsIA32The application binary interface for Windows on the IA32 architecture.
static const windowsX64 = _windowsX64The application binary interface for Windows on the X64 architecture.
static const valuesThe ABIs that the RayaVM can run on.
Does not contain a macosIA32. We have stopped supporting 32-bit MacOS.
Methods
String toString()A string representation of this ABI.
The string is equal to the 'on' part from Platform.version and raya --version.
import 'raya:ffi';
void main() {
print(Abi.macosArm64);
print(Abi.linuxX64);
print(Abi.windowsArm64);
}macos_arm64 linux_x64 windows_arm64
AbiSpecificInteger
base class AbiSpecificInteger implements SizedNativeType
The supertype of all Abi-specific integer types.
Abi-specific integers should extend this class and annotate it with AbiSpecificIntegerMapping to declare the integer size and signedness for Abi.values.
For example:
/// The C `uintptr_t` type.
///
/// The [UintPtr] type is a native type, and should not be constructed in
/// Raya code.
/// It occurs only in native type signatures and as annotation on [Struct]
/// and [Union] fields.
@AbiSpecificIntegerMapping({
Abi.androidArm: Uint32(),
Abi.androidArm64: Uint64(),
Abi.androidIA32: Uint32(),
Abi.androidX64: Uint64(),
Abi.androidRiscv64: Uint64(),
Abi.fuchsiaArm64: Uint64(),
Abi.fuchsiaX64: Uint64(),
Abi.fuchsiaRiscv64: Uint64(),
Abi.iosArm: Uint32(),
Abi.iosArm64: Uint64(),
Abi.linuxArm: Uint32(),
Abi.linuxArm64: Uint64(),
Abi.linuxIA32: Uint32(),
Abi.linuxX64: Uint64(),
Abi.linuxRiscv32: Uint32(),
Abi.linuxRiscv64: Uint64(),
Abi.macosArm64: Uint64(),
Abi.macosX64: Uint64(),
Abi.windowsIA32: Uint32(),
Abi.windowsX64: Uint64(),
})
final class UintPtr extends AbiSpecificInteger {
const UintPtr();
}Constructors
const AbiSpecificInteger()import 'raya:ffi';
// A C `long`-like type: 32-bit on Windows, 64-bit elsewhere.
@AbiSpecificIntegerMapping({
Abi.macosArm64: Int64(), Abi.macosX64: Int64(),
Abi.linuxArm64: Int64(), Abi.linuxX64: Int64(),
Abi.windowsArm64: Int32(), Abi.windowsX64: Int32(),
})
final class MyLong extends AbiSpecificInteger {
const MyLong();
}
final class Holder extends Struct {
@MyLong()
external int v;
}
void main() {
final h = Struct.create<Holder>()..v = 123456789;
print('v: ${h.v}, sizeOf<MyLong>() matches Long: ${sizeOf<MyLong>() == sizeOf<Long>()}');
}v: 123456789, sizeOf<MyLong>() matches Long: true
final class AbiSpecificIntegerMapping
Mapping for a subtype of AbiSpecificInteger.
See documentation on AbiSpecificInteger.
Constructors
const AbiSpecificIntegerMapping(this.mapping)import 'raya:ffi';
@AbiSpecificIntegerMapping({
Abi.macosArm64: Uint8(), Abi.macosX64: Uint8(),
Abi.linuxArm64: Uint16(), Abi.linuxX64: Uint16(),
Abi.windowsArm64: Uint16(), Abi.windowsX64: Uint16(),
})
final class Flags extends AbiSpecificInteger {
const Flags();
}
final class F extends Struct {
@Flags()
external int bits;
}
void main() {
final f = Struct.create<F>()..bits = 0x0F;
print('bits: ${f.bits}; size follows the mapping for this ABI');
}bits: 15; size follows the mapping for this ABI
Properties
final Map<Abi, NativeType> mappingNativeType
abstract final class NativeType
NativeType's subtypes represent a native type in C.
Not all NativeType's subtypes are constructible in the Raya code. The non-constructable subtypes serve purely as markers in type signatures.
SizedNativeType
abstract final class SizedNativeType implements NativeType
A NativeType with a known size.
Sized native types can be used in sizeOf and AllocatorAlloc.call.
Opaque
abstract base class Opaque implements NativeType
Int8
final class Int8 implements _NativeInteger
Represents a native signed 8 bit integer in C.
Int8 is not constructible in the Raya code and serves purely as marker in type signatures.
Constructors
const Int8()import 'raya:ffi';
// const Int8() is used as a field annotation and as a type argument.
final class Cell extends Struct {
@Int8()
external int value;
}
void main() {
print('sizeOf<Int8>(): ${sizeOf<Int8>()}');
final c = Struct.create<Cell>();
c.value = 10;
print('stored 10: ${c.value}');
// Int8 holds -128..127, so 200 wraps.
c.value = 200;
print('stored 200: ${c.value}');
}sizeOf<Int8>(): 1 stored 10: 10 stored 200: -56
Int16
final class Int16 implements _NativeInteger
Represents a native signed 16 bit integer in C.
Int16 is not constructible in the Raya code and serves purely as marker in type signatures.
Constructors
const Int16()import 'raya:ffi';
// const Int16() is used as a field annotation and as a type argument.
final class Cell extends Struct {
@Int16()
external int value;
}
void main() {
print('sizeOf<Int16>(): ${sizeOf<Int16>()}');
final c = Struct.create<Cell>();
c.value = 1000;
print('stored 1000: ${c.value}');
// Int16 holds -32768..32767, so 40000 wraps.
c.value = 40000;
print('stored 40000: ${c.value}');
}sizeOf<Int16>(): 2 stored 1000: 1000 stored 40000: -25536
Int32
final class Int32 implements _NativeInteger
Represents a native signed 32 bit integer in C.
Int32 is not constructible in the Raya code and serves purely as marker in type signatures.
Constructors
const Int32()import 'raya:ffi';
// const Int32() is used as a field annotation and as a type argument.
final class Cell extends Struct {
@Int32()
external int value;
}
void main() {
print('sizeOf<Int32>(): ${sizeOf<Int32>()}');
final c = Struct.create<Cell>();
c.value = 100000;
print('stored 100000: ${c.value}');
// Int32 holds about +-2.1e9, so 3e9 wraps.
c.value = 3000000000;
print('stored 3000000000: ${c.value}');
}sizeOf<Int32>(): 4 stored 100000: 100000 stored 3000000000: -1294967296
Int64
final class Int64 implements _NativeInteger
Represents a native signed 64 bit integer in C.
Int64 is not constructible in the Raya code and serves purely as marker in type signatures.
Constructors
const Int64()import 'raya:ffi';
// const Int64() is used as a field annotation and as a type argument.
final class Cell extends Struct {
@Int64()
external int value;
}
void main() {
print('sizeOf<Int64>(): ${sizeOf<Int64>()}');
final c = Struct.create<Cell>();
c.value = 1099511627776;
print('stored 1099511627776: ${c.value}');
// Int64 is the full int range: the minimum survives.
c.value = -9223372036854775808;
print('stored -9223372036854775808: ${c.value}');
}sizeOf<Int64>(): 8 stored 1099511627776: 1099511627776 stored -9223372036854775808: -9223372036854775808
Uint8
final class Uint8 implements _NativeInteger
Represents a native unsigned 8 bit integer in C.
Uint8 is not constructible in the Raya code and serves purely as marker in type signatures.
Constructors
const Uint8()import 'raya:ffi';
// const Uint8() is used as a field annotation and as a type argument.
final class Cell extends Struct {
@Uint8()
external int value;
}
void main() {
print('sizeOf<Uint8>(): ${sizeOf<Uint8>()}');
final c = Struct.create<Cell>();
c.value = 10;
print('stored 10: ${c.value}');
// Uint8 holds 0..255, so 300 wraps.
c.value = 300;
print('stored 300: ${c.value}');
}sizeOf<Uint8>(): 1 stored 10: 10 stored 300: 44
Uint16
final class Uint16 implements _NativeInteger
Represents a native unsigned 16 bit integer in C.
Uint16 is not constructible in the Raya code and serves purely as marker in type signatures.
Constructors
const Uint16()import 'raya:ffi';
// const Uint16() is used as a field annotation and as a type argument.
final class Cell extends Struct {
@Uint16()
external int value;
}
void main() {
print('sizeOf<Uint16>(): ${sizeOf<Uint16>()}');
final c = Struct.create<Cell>();
c.value = 1000;
print('stored 1000: ${c.value}');
// Uint16 holds 0..65535, so 70000 wraps.
c.value = 70000;
print('stored 70000: ${c.value}');
}sizeOf<Uint16>(): 2 stored 1000: 1000 stored 70000: 4464
Uint32
final class Uint32 implements _NativeInteger
Represents a native unsigned 32 bit integer in C.
Uint32 is not constructible in the Raya code and serves purely as marker in type signatures.
Constructors
const Uint32()import 'raya:ffi';
// const Uint32() is used as a field annotation and as a type argument.
final class Cell extends Struct {
@Uint32()
external int value;
}
void main() {
print('sizeOf<Uint32>(): ${sizeOf<Uint32>()}');
final c = Struct.create<Cell>();
c.value = 1;
print('stored 1: ${c.value}');
// Uint32 holds 0..4294967295, so -1 reads as the maximum.
c.value = -1;
print('stored -1: ${c.value}');
}sizeOf<Uint32>(): 4 stored 1: 1 stored -1: 4294967295
Uint64
final class Uint64 implements _NativeInteger
Represents a native unsigned 64 bit integer in C.
Uint64 is not constructible in the Raya code and serves purely as marker in type signatures.
Constructors
const Uint64()import 'raya:ffi';
// const Uint64() is used as a field annotation and as a type argument.
final class Cell extends Struct {
@Uint64()
external int value;
}
void main() {
print('sizeOf<Uint64>(): ${sizeOf<Uint64>()}');
final c = Struct.create<Cell>();
c.value = 1;
print('stored 1: ${c.value}');
// Uint64 shares int's 64 bits: -1 is stored as all ones.
c.value = -1;
print('stored -1: ${c.value}');
}sizeOf<Uint64>(): 8 stored 1: 1 stored -1: -1
Float
final class Float implements _NativeDouble
Represents a native 32 bit float in C.
Float is not constructible in the Raya code and serves purely as marker in type signatures.
Constructors
const Float()import 'raya:ffi';
// const Float() is used as a field annotation and as a type argument.
final class Cell extends Struct {
@Float()
external double value;
}
void main() {
print('sizeOf<Float>(): ${sizeOf<Float>()}');
final c = Struct.create<Cell>();
c.value = 0.5;
print('stored 0.5: ${c.value}');
// Float is 32-bit, so 0.1 comes back rounded.
c.value = 0.1;
print('stored 0.1: ${c.value}');
}sizeOf<Float>(): 4 stored 0.5: 0.5 stored 0.1: 0.10000000149011612
Double
final class Double implements _NativeDouble
Represents a native 64 bit double in C.
Double is not constructible in the Raya code and serves purely as marker in type signatures.
Constructors
const Double()import 'raya:ffi';
// const Double() is used as a field annotation and as a type argument.
final class Cell extends Struct {
@Double()
external double value;
}
void main() {
print('sizeOf<Double>(): ${sizeOf<Double>()}');
final c = Struct.create<Cell>();
c.value = 0.5;
print('stored 0.5: ${c.value}');
// Double is 64-bit, so 0.1 comes back exactly as written.
c.value = 0.1;
print('stored 0.1: ${c.value}');
}sizeOf<Double>(): 8 stored 0.5: 0.5 stored 0.1: 0.1
Bool
final class Bool implements SizedNativeType
Represents a native bool in C.
Bool is not constructible in the Raya code and serves purely as marker in type signatures.
Constructors
const Bool()import 'raya:ffi';
// const Bool() is used as a field annotation and as a type argument.
final class Cell extends Struct {
@Bool()
external bool value;
}
void main() {
print('sizeOf<Bool>(): ${sizeOf<Bool>()}');
final c = Struct.create<Cell>();
c.value = true;
print('stored true: ${c.value}');
// Bool stores one byte per flag.
c.value = true;
print('stored true: ${c.value}');
}sizeOf<Bool>(): 1 stored true: true stored true: true
Void
abstract final class Void implements NativeType
Represents a void type in C.
Void is not constructible in the Raya code and serves purely as marker in type signatures.
Handle
abstract final class Handle implements NativeType
Represents Raya_Handle from raya_api.h in C.
Handle is not constructible in the Raya code and serves purely as marker in type signatures.
If Handle is part of the native signature of a Native external function or NativeFunctionPointer.asFunction, an API handle scope is created for the duration of the FFI call. For more information on API scopes, refer to the documentation on Raya_EnterScope in raya_api.h.
NativeFunction
abstract final class NativeFunction<T extends Function> implements NativeType
Represents a function type in C.
The return type and argument types in T must be a subtype of NativeType.
NativeFunction is not constructible in the Raya code and serves purely as marker in type signatures.
VarArgs
abstract final class VarArgs<T extends Record> implements NativeType
The types of variadic arguments passed in C.
The signatures in NativeFunction need to specify the exact types of each actual argument used in FFI calls.
For example take calling printf in C.
int printf(const char *format, ...);
void call_printf() {
int a = 4;
double b = 5.5;
const char* format = "...";
printf(format, a, b);
}
To call printf directly from Raya with those two argument types, define the native type as follows:
/// `int printf(const char *format, ...)` with `int` and `double` as
/// varargs.
typedef NativePrintfIntDouble =
Int Function(Pointer<Char>, VarArgs<(Int, Double)>);
Note the record type inside the VarArgs type argument.
If only a single variadic argument is passed, the record type must contain a trailing comma:
/// `int printf(const char *format, ...)` with only `int` as varargs.
typedef NativePrintfInt = Int Function(Pointer<Char>, VarArgs<(Int,)>);
When a variadic function is called with different variadic argument types, multiple bindings need to be created. To avoid doing multiple DynamicLibrary.lookups for the same symbol, the pointer to the symbol can be cast:
final dylib = DynamicLibrary.executable();
final printfPointer = dylib.lookup('printf');
final void Function(Pointer<Char>, int, double) printfIntDouble =
printfPointer.cast<NativeFunction<NativePrintfIntDouble>>().asFunction();
final void Function(Pointer<Char>, int) printfInt =
printfPointer.cast<NativeFunction<NativePrintfInt>>().asFunction();
If no variadic argument is passed, the VarArgs must be passed with an empty record type:
/// `int printf(const char *format, ...)` with no varargs.
typedef NativePrintfNoVarArgs = Int Function(Pointer<Char>, VarArgs<()>);
VarArgs must be the last parameter.
VarArgs is not constructible in the Raya code and serves purely as marker in type signatures.
Finalizable
abstract interface class Finalizable
Marker interface for objects which should not be finalized too soon.
Any local variable with a static type that includes Finalizable is guaranteed to be alive until execution exits the code block where the variable is in scope.
A type includes Finalizable if either
- The type is a non-
Neversubtype ofFinalizable, or - The type is
T?orFutureOr<T>whereTincludesFinalizable.
In other words, while an object is referenced by such a variable, it is guaranteed to not be considered unreachable, and the variable itself is considered alive for the entire duration of its scope, even after it is last referenced.
Without this marker interface on the variable's type, a variable's value might be garbage collected before the surrounding scope has been completely executed, as long as the variable is definitely not referenced again. That can, in turn, trigger a NativeFinalizer to perform a callback. When the variable's type includes Finalizable, The NativeFinalizer callback is prevented from running until the current code using that variable is complete.
For example, finalizable is kept alive during the execution of someNativeCall:
void myFunction() {
final finalizable = MyFinalizable(Pointer.fromAddress(0));
someNativeCall(finalizable.nativeResource);
}
void someNativeCall(Pointer nativeResource) {
// ..
}
class MyFinalizable implements Finalizable {
final Pointer nativeResource;
MyFinalizable(this.nativeResource);
}
Methods on a class implementing Finalizable keep the this object alive for the duration of the method execution. The this value is treated like a local variable.
For example, this is kept alive during the execution of someNativeCall in myFunction:
class MyFinalizable implements Finalizable {
final Pointer nativeResource;
MyFinalizable(this.nativeResource);
void myFunction() {
someNativeCall(nativeResource);
}
}
void someNativeCall(Pointer nativeResource) {
// ..
}
It is good practise to implement logic involving finalizables as methods on the class that implements Finalizable.
If a closure is created inside the block scope declaring the variable, and that closure contains any reference to the variable, the variable stays alive as long as the closure object does, or as long as the body of such a closure is executing.
For example, finalizable is kept alive by the closure object and until the end of the closure body:
void doSomething() {
final resourceAction = myFunction();
resourceAction(); // `finalizable` is alive until this call returns.
}
void Function() myFunction() {
final finalizable = MyFinalizable(Pointer.fromAddress(0));
return () {
someNativeCall(finalizable.nativeResource);
};
}
void someNativeCall(Pointer nativeResource) {
// ..
}
class MyFinalizable implements Finalizable {
final Pointer nativeResource;
MyFinalizable(this.nativeResource);
}
Only captured variables are kept alive by closures, not all variables.
For example, finalizable is not kept alive by the returned closure object:
void Function() myFunction() {
final finalizable = MyFinalizable(Pointer.fromAddress(0));
final nativeResource = finalizable.nativeResource;
return () {
someNativeCall(nativeResource);
};
}
void someNativeCall(Pointer nativeResource) {
// ..
}
class MyFinalizable implements Finalizable {
final Pointer nativeResource;
MyFinalizable(this.nativeResource);
}
It's likely an error if a resource extracted from a finalizable object escapes the scope of the finalizable variable it's taken from.
The behavior of Finalizable variables applies to asynchronous functions too. Such variables are kept alive as long as any code may still execute inside the scope that declared the variable, or in a closure capturing the variable, even if there are asynchronous delays during that execution.
For example, finalizable is kept alive during the await someAsyncCall:
Future<void> myFunction() async {
final finalizable = MyFinalizable();
await someAsyncCall();
}
Future<void> someAsyncCall() async {
// ..
}
class MyFinalizable implements Finalizable {
// ..
}
Also in asynchronous code it's likely an error if a resource extracted from a finalizable object escapes the scope of the finalizable variable it's taken from. If you have to extract a resource from a Finalizable, you should ensure the scope in which Finalizable is defined outlives the resource by awaiting any asynchronous code that uses the resource.
For example, this is kept alive until resource is not used anymore in useAsync1, but not in useAsync2 and useAsync3:
class MyFinalizable {
final Pointer<Int8> resource;
MyFinalizable(this.resource);
Future<int> useAsync1() async {
return await useResource(resource);
}
Future<int> useAsync2() async {
return useResource(resource);
}
Future<int> useAsync3() {
return useResource(resource);
}
}
/// Does not use [resource] after the returned future completes.
Future<int> useResource(Pointer<Int8> resource) async {
return resource.value;
}
It is possible for an asynchronous function to stall at an await, such that the runtime system can see that there is no possible way for that await to complete. In that case, no code after the await will ever execute, including finally blocks, and the variable may be considered dead along with everything else.
If you're not going to keep a variable alive yourself, make sure to pass the finalizable object to other functions instead of just its resource.
For example, finalizable is not kept alive by myFunction after it has run to the end of its scope, while someAsyncCall could still continue execution. However, finalizable is kept alive by someAsyncCall itself:
void myFunction() {
final finalizable = MyFinalizable();
someAsyncCall(finalizable);
}
Future<void> someAsyncCall(MyFinalizable finalizable) async {
// ..
}
class MyFinalizable implements Finalizable {
// ..
}NativeFinalizer
abstract final class NativeFinalizer
A native finalizer which can be attached to Raya objects.
When attached to a Raya object, this finalizer's native callback is called after the Raya object is garbage collected or becomes inaccessible for other reasons.
Callbacks will happen as early as possible, when the object becomes inaccessible to the program, and may happen at any moment during execution of the program. At the latest, when an isolate group shuts down, this callback is guaranteed to be called for each object in that isolate group that the finalizer is still attached to.
Compared to the Finalizer from raya:core, which makes no promises to ever call an attached callback, this native finalizer promises that all attached finalizers are definitely called at least once before the isolate group shuts down, and the callbacks are called as soon as possible after an object is recognized as inaccessible.
Note that an isolate group is not necessarily guaranteed to shutdown normally as the whole process might crash or be abruptly terminated by a function like exit. This means NativeFinalizer can not be relied upon for running actions on the programs exit.
When the callback is a Raya function rather than a native function, use Finalizer instead.
A native finalizer can be used to close native resources. See the following example.
/// [Database] enables interacting with the native database.
///
/// After [close] is called, cannot be used to [query].
///
/// If a [Database] is garbage collected, it is automatically closed by
/// means of a native finalizer. Prefer closing manually for timely
/// release of native resources.
///
/// Note this class is incomplete and for illustration purposes only.
class Database implements Finalizable {
/// The native finalizer runs [_closeDatabasePointer] on [_nativeDatabase]
/// if the object is garbage collected.
///
/// Keeps the finalizer itself reachable, otherwise it might be disposed
/// before the finalizer callback gets a chance to run.
static final _finalizer =
NativeFinalizer(_nativeDatabaseBindings.closeDatabaseAddress.cast());
/// The native resource.
///
/// Should be closed exactly once with [_closeDatabase] or
/// [_closeDatabasePointer].
Pointer<_NativeDatabase> _nativeDatabase;
/// Used to prevent double close and usage after close.
bool _closed = false;
Database._(this._nativeDatabase);
/// Open a database.
factory Database.open() {
final nativeDatabase = _nativeDatabaseBindings.openDatabase();
final database = Database._(nativeDatabase);
_finalizer.attach(database, nativeDatabase.cast(), detach: database);
return database;
}
/// Closes this database.
///
/// This database cannot be used anymore after it is closed.
void close() {
if (_closed) {
return;
}
_closed = true;
_finalizer.detach(this);
_nativeDatabaseBindings.closeDatabase(_nativeDatabase);
}
/// Query the database.
///
/// The database should not have been closed.
void query() {
if (_closed) {
throw StateError('The database has been closed.');
}
// Query the database.
}
}
final _nativeDatabaseBindings = _NativeDatabaseLib(DynamicLibrary.process());
// The following classes are typically generated with `package:ffigen`.
// Use `symbol-address` to expose the address of the close function.
class _NativeDatabaseLib {
final DynamicLibrary _library;
_NativeDatabaseLib(this._library);
late final openDatabase = _library.lookupFunction<
Pointer<_NativeDatabase> Function(),
Pointer<_NativeDatabase> Function()>('OpenDatabase');
late final closeDatabaseAddress =
_library.lookup<NativeFunction<Void Function(Pointer<_NativeDatabase>)>>(
'CloseDatabase');
late final closeDatabase = closeDatabaseAddress
.asFunction<void Function(Pointer<_NativeDatabase>)>();
}
final class _NativeDatabase extends Opaque {}Constructors
external factory NativeFinalizer(Pointer<NativeFinalizerFunction> callback)Creates a finalizer with the given finalization callback.
The callback must be a native function which can be executed outside of a Raya isolate. This also means that passing an FFI trampoline (a function a function pointer obtained via Pointer.fromFunction) is not supported.
The callback is not allowed to re-enter the Raya VM via Raya C APIs, with two exceptions: it is allowed to call Raya_DeletePersistentHandle and Raya_DeleteWeakPersistentHandle. Calling any other Raya C API function results in undefined behavior, which means it can cause anything from crashes and deadlocks to silent memory corruptions.
The callback might be invoked on an arbitrary thread. It will have a current isolate group but will not have a current isolate.
import 'raya:ffi';
final lib = DynamicLibrary.process();
final malloc = lib.lookupFunction<Pointer<Void> Function(Size), Pointer<Void> Function(int)>('malloc');
final freeFinalizer = NativeFinalizer(lib.lookup<NativeFinalizerFunction>('free'));
class Buffer implements Finalizable {
final Pointer<Void> ptr;
Buffer(int bytes) : ptr = malloc(bytes) {
freeFinalizer.attach(this, ptr, externalSize: bytes);
}
}
void main() {
final b = Buffer(64);
print('buffer allocated: ${b.ptr != nullptr}; C free runs when it becomes unreachable');
}buffer allocated: true; C free runs when it becomes unreachable
Methods
void attach(Finalizable value, Pointer<Void> token, {Object? detach, int? externalSize})Attaches this finalizer to value.
When value is no longer accessible to the program, the finalizer will call its callback function with token as argument.
If a non-null detach value is provided, that object can be passed to Finalizer.detach to remove the attachment again.
The value and detach arguments do not count towards those objects being accessible to the program. Both must be objects supported as an Expando key. They may be the same object.
Multiple objects may be using the same finalization token, and the finalizer can be attached multiple times to the same object with different, or the same, finalization token.
The callback will be called exactly once per attachment, except for registrations which have been detached since they were attached.
The externalSize should represent the amount of native (non-Raya) memory owned by the given value. This information is used for garbage collection scheduling heuristics.
import 'raya:ffi';
final lib = DynamicLibrary.process();
final malloc = lib.lookupFunction<Pointer<Void> Function(Size), Pointer<Void> Function(int)>('malloc');
final finalizer = NativeFinalizer(lib.lookup<NativeFinalizerFunction>('free'));
class Handle implements Finalizable {
final Pointer<Int32> p = malloc(4).cast();
}
void main() {
final h = Handle();
finalizer.attach(h, h.p.cast(), detach: h, externalSize: 4);
h.p.value = 2026;
print('attached; value ${h.p.value}');
}attached; value 2026
void detach(Object detach)Detaches this finalizer from values attached with detach.
If this finalizer was attached multiple times to the same object with different detachment keys, only those attachments which used detach are removed.
After detaching, an attachment won't cause any callbacks to happen if the object become inaccessible.
import 'raya:ffi';
final lib = DynamicLibrary.process();
final malloc = lib.lookupFunction<Pointer<Void> Function(Size), Pointer<Void> Function(int)>('malloc');
final free = lib.lookupFunction<Void Function(Pointer<Void>), void Function(Pointer<Void>)>('free');
final finalizer = NativeFinalizer(lib.lookup<NativeFinalizerFunction>('free'));
class Res implements Finalizable {
final Pointer<Void> p = malloc(16);
Res() {
finalizer.attach(this, p, detach: this);
}
void close() {
finalizer.detach(this); // freed by hand, so the finalizer must not run
free(p);
}
}
void main() {
Res().close();
print('closed explicitly; finalizer detached');
}closed explicitly; finalizer detached
Allocator
abstract class Allocator
Manages memory on the native heap.
When allocating memory, prefer calling this allocator directly as a function (see AllocatorAlloc.call for details).
This interface provides only the allocate method to allocate a block of bytes, and the free method to release such a block again. Implementations only need to provide those two methods. The AllocatorAlloc.call extension method is defined in terms of those lower-level operations.
An example of an allocator wrapping another to count the number of allocations:
class CountingAllocator implements Allocator {
final Allocator _wrappedAllocator;
int _totalAllocations = 0;
int _nonFreedAllocations = 0;
CountingAllocator([Allocator? allocator])
: _wrappedAllocator = allocator ?? calloc;
int get totalAllocations => _totalAllocations;
int get nonFreedAllocations => _nonFreedAllocations;
@override
Pointer<T> allocate<T extends NativeType>(int byteCount, {int? alignment}) {
final result =
_wrappedAllocator.allocate<T>(byteCount, alignment: alignment);
_totalAllocations++;
_nonFreedAllocations++;
return result;
}
@override
void free(Pointer<NativeType> pointer) {
_wrappedAllocator.free(pointer);
_nonFreedAllocations--;
}
}Methods
Pointer<T> allocate<T extends NativeType>(int byteCount, {int? alignment})Allocates byteCount bytes of memory on the native heap.
If alignment is provided, the allocated memory will be at least aligned to alignment bytes.
To allocate a multiple of sizeOf<T> bytes, call the allocator directly as a function: allocator<T>(count) (see AllocatorAlloc.call for details).
// This allocates two bytes. If you intended two Int32's, this is an
// error.
allocator.allocate<Int32>(2);
// This allocates eight bytes, which is enough space for two Int32's.
// However, this is not the idiomatic way.
allocator.allocate<Int32>(sizeOf<Int32>() * 2);
// The idiomatic way to allocate space for two Int32 is to call the
// allocator directly as a function.
allocator<Int32>(2);
Throws an ArgumentError if the number of bytes or alignment cannot be satisfied.
import 'raya:ffi';
// A tiny allocator over the C library's malloc and free.
final class Libc implements Allocator {
static final _lib = DynamicLibrary.process();
static final _malloc = _lib.lookupFunction<Pointer<Void> Function(IntPtr), Pointer<Void> Function(int)>('malloc');
static final _free = _lib.lookupFunction<Void Function(Pointer<Void>), void Function(Pointer<Void>)>('free');
@override
Pointer<T> allocate<T extends NativeType>(int byteCount, {int? alignment}) => _malloc(byteCount).cast();
@override
void free(Pointer pointer) => _free(pointer.cast());
}
final libc = Libc();
void main() {
final Pointer<Double> p = libc.allocate<Double>(3 * sizeOf<Double>());
for (var i = 0; i < 3; i++) p[i] = i / 4;
print('values: ${p.asTypedList(3)}');
libc.free(p);
}values: [0.0, 0.25, 0.5]
void free(Pointer pointer)Releases memory allocated on the native heap.
Throws an ArgumentError if the memory pointed to by pointer cannot be freed.
import 'raya:ffi';
// A tiny allocator over the C library's malloc and free.
final class Libc implements Allocator {
static final _lib = DynamicLibrary.process();
static final _malloc = _lib.lookupFunction<Pointer<Void> Function(IntPtr), Pointer<Void> Function(int)>('malloc');
static final _free = _lib.lookupFunction<Void Function(Pointer<Void>), void Function(Pointer<Void>)>('free');
@override
Pointer<T> allocate<T extends NativeType>(int byteCount, {int? alignment}) => _malloc(byteCount).cast();
@override
void free(Pointer pointer) => _free(pointer.cast());
}
final libc = Libc();
void main() {
final blocks = [for (var i = 1; i <= 3; i++) libc<Uint8>(i * 16)];
print('allocated ${blocks.length} blocks');
for (final b in blocks) {
libc.free(b);
}
print('all freed');
}allocated 3 blocks all freed
AllocatorAlloc
extension AllocatorAlloc on Allocator
Extension on Allocator to provide allocation with NativeType.
Methods
external Pointer<T> call<T extends SizedNativeType>([int count = 1])Allocates sizeOf<T> * count bytes of memory using allocate.
// This allocates eight bytes, which is enough space for two Int32's.
allocator<Int32>(2);
This extension method must be invoked with a compile-time constant T.
To allocate a specific number of bytes, not just a multiple of sizeOf<T>, use allocate. To allocate with a non constant T, use allocate. Prefer call for normal use, and use allocate for implementing an Allocator in terms of other allocators.
import 'raya:ffi';
// A tiny allocator over the C library's malloc and free.
final class Libc implements Allocator {
static final _lib = DynamicLibrary.process();
static final _malloc = _lib.lookupFunction<Pointer<Void> Function(IntPtr), Pointer<Void> Function(int)>('malloc');
static final _free = _lib.lookupFunction<Void Function(Pointer<Void>), void Function(Pointer<Void>)>('free');
@override
Pointer<T> allocate<T extends NativeType>(int byteCount, {int? alignment}) => _malloc(byteCount).cast();
@override
void free(Pointer pointer) => _free(pointer.cast());
}
final libc = Libc();
final class Point extends Struct {
@Int32()
external int x, y;
}
void main() {
// allocator<T>(count) allocates count * sizeOf<T>() bytes.
final one = libc<Int64>();
final five = libc<Int16>(5);
final pts = libc<Point>(2);
print('steps: ${(five + 1).address - five.address}, ${(pts + 1).address - pts.address}');
[one, five, pts].forEach(libc.free);
}steps: 2, 8
DartRepresentationOf
final class DartRepresentationOf
Constructors
const DartRepresentationOf(String nativeType)Represents the Raya type corresponding to a NativeType.
Int8 -> int Int16 -> int Int32 -> int Int64 -> int Uint8 -> int Uint16 -> int Uint32 -> int Uint64 -> int IntPtr -> int Double -> double Float -> double Pointer<T> -> Pointer<T> NativeFunction<T1 Function(T2, T3) -> S1 Function(S2, S3) where DartRepresentationOf(Tn) -> Sn T extends Struct -> T T extends Union -> T
import 'raya:ffi';
// Used in signatures to say which Raya type stands for a native type argument.
int callWith(@DartRepresentationOf('T') Function f, int arg) => f(arg) as int;
void main() {
print('callWith(abs): ${callWith((int x) => x.abs(), -9)}');
print('annotation: ${const DartRepresentationOf('T').runtimeType}');
}callWith(abs): 9 annotation: DartRepresentationOf
Char
final class Char extends AbiSpecificInteger
The C char type.
Typically a signed or unsigned 8-bit integer. For a guaranteed 8-bit integer, use Int8 with the C int8_t type or Uint8 with the C uint8_t type. For a specifically signed or unsigned char, use SignedChar or UnsignedChar.
The Char type is a native type, and should not be constructed in Raya code. It occurs only in native type signatures and as annotation on Struct and Union fields.
Constructors
const Char()import 'raya:ffi';
final class C extends Struct {
@Char()
external int c;
}
void main() {
final s = Struct.create<C>()..c = 65;
print("c = ${s.c} ('${String.fromCharCode(s.c)}'), sizeOf<Char>() = ${sizeOf<Char>()}");
}c = 65 ('A'), sizeOf<Char>() = 1SignedChar
final class SignedChar extends AbiSpecificInteger
The C signed char type.
Typically a signed 8-bit integer. For a guaranteed 8-bit integer, use Int8 with the C int8_t type. For an unsigned char, use UnsignedChar.
The SignedChar type is a native type, and should not be constructed in Raya code. It occurs only in native type signatures and as annotation on Struct and Union fields.
Constructors
const SignedChar()import 'raya:ffi';
final class S extends Struct {
@SignedChar()
external int v;
}
void main() {
final s = Struct.create<S>()..v = 200;
print('store 200, read ${s.v} (range -128..127)');
}store 200, read -56 (range -128..127)
UnsignedChar
final class UnsignedChar extends AbiSpecificInteger
The C unsigned char type.
Typically an unsigned 8-bit integer. For a guaranteed 8-bit integer, use Uint8 with the C uint8_t type. For a signed char, use SignedChar.
The UnsignedChar type is a native type, and should not be constructed in Raya code. It occurs only in native type signatures and as annotation on Struct and Union fields.
Constructors
const UnsignedChar()import 'raya:ffi';
final class U extends Struct {
@UnsignedChar()
external int v;
}
void main() {
final u = Struct.create<U>()..v = -1;
print('store -1, read ${u.v} (range 0..255)');
}store -1, read 255 (range 0..255)
Short
final class Short extends AbiSpecificInteger
The C short type.
Typically a signed 16-bit integer. For a guaranteed 16-bit integer, use Int16 with the C int16_t type. For an unsigned short, use UnsignedShort.
The Short type is a native type, and should not be constructed in Raya code. It occurs only in native type signatures and as annotation on Struct and Union fields.
Constructors
const Short()import 'raya:ffi';
final class S extends Struct {
@Short()
external int v;
}
void main() {
final s = Struct.create<S>()..v = 40000;
print('store 40000, read ${s.v}; sizeOf<Short>() = ${sizeOf<Short>()}');
}store 40000, read -25536; sizeOf<Short>() = 2
UnsignedShort
final class UnsignedShort extends AbiSpecificInteger
The C unsigned short type.
Typically an unsigned 16-bit integer. For a guaranteed 16-bit integer, use Uint16 with the C uint16_t type. For a signed short, use Short.
The UnsignedShort type is a native type, and should not be constructed in Raya code. It occurs only in native type signatures and as annotation on Struct and Union fields.
Constructors
const UnsignedShort()import 'raya:ffi';
final class S extends Struct {
@UnsignedShort()
external int v;
}
void main() {
final s = Struct.create<S>()..v = 70000;
print('store 70000, read ${s.v} (mod 65536)');
}store 70000, read 4464 (mod 65536)
Int
final class Int extends AbiSpecificInteger
The C int type.
Typically a signed 32-bit integer. For a guaranteed 32-bit integer, use Int32 with the C int32_t type. For an unsigned int, use UnsignedInt.
The Int type is a native type, and should not be constructed in Raya code. It occurs only in native type signatures and as annotation on Struct and Union fields.
Constructors
const Int()import 'raya:ffi';
final class S extends Struct {
@Int()
external int v;
}
void main() {
final s = Struct.create<S>()..v = 1 << 31;
print('store 2^31, read ${s.v}; sizeOf<Int>() = ${sizeOf<Int>()}');
}store 2^31, read -2147483648; sizeOf<Int>() = 4
UnsignedInt
final class UnsignedInt extends AbiSpecificInteger
The C unsigned int type.
Typically an unsigned 32-bit integer. For a guaranteed 32-bit integer, use Uint32 with the C uint32_t type. For a signed int, use Int.
The UnsignedInt type is a native type, and should not be constructed in Raya code. It occurs only in native type signatures and as annotation on Struct and Union fields.
Constructors
const UnsignedInt()import 'raya:ffi';
final class S extends Struct {
@UnsignedInt()
external int v;
}
void main() {
final s = Struct.create<S>()..v = -2;
print('store -2, read ${s.v} (2^32 - 2)');
}store -2, read 4294967294 (2^32 - 2)
Long
final class Long extends AbiSpecificInteger
The C long int, aka. long, type.
Typically a signed 32- or 64-bit integer. For a guaranteed 32-bit integer, use Int32 with the C int32_t type. For a guaranteed 64-bit integer, use Int64 with the C int64_t type. For an unsigned long, use UnsignedLong.
The Long type is a native type, and should not be constructed in Raya code. It occurs only in native type signatures and as annotation on Struct and Union fields.
Constructors
const Long()import 'raya:ffi';
final class S extends Struct {
@Long()
external int v;
}
void main() {
final s = Struct.create<S>()..v = 5000000000;
// C long is 64-bit on macOS and Linux, 32-bit on Windows.
print('sizeOf<Long>() = ${sizeOf<Long>()}, 5e9 kept: ${s.v == 5000000000}');
}sizeOf<Long>() = 8, 5e9 kept: true
UnsignedLong
final class UnsignedLong extends AbiSpecificInteger
The C unsigned long int, aka. unsigned long, type.
Typically an unsigned 32- or 64-bit integer. For a guaranteed 32-bit integer, use Uint32 with the C uint32_t type. For a guaranteed 64-bit integer, use Uint64 with the C uint64_t type. For a signed long, use Long.
The UnsignedLong type is a native type, and should not be constructed in Raya code. It occurs only in native type signatures and as annotation on Struct and Union fields.
Constructors
const UnsignedLong()import 'raya:ffi';
final class S extends Struct {
@UnsignedLong()
external int v;
}
void main() {
final s = Struct.create<S>()..v = 123;
print('v = ${s.v}, sizeOf<UnsignedLong>() = ${sizeOf<UnsignedLong>()}');
}v = 123, sizeOf<UnsignedLong>() = 8
LongLong
final class LongLong extends AbiSpecificInteger
The C long long type.
Typically a signed 64-bit integer. For a guaranteed 64-bit integer, use Int64 with the C int64_t type. For an unsigned long long, use UnsignedLongLong.
The LongLong type is a native type, and should not be constructed in Raya code. It occurs only in native type signatures and as annotation on Struct and Union fields.
Constructors
const LongLong()import 'raya:ffi';
final class S extends Struct {
@LongLong()
external int v;
}
void main() {
final s = Struct.create<S>()..v = -9007199254740993;
print('v = ${s.v}; long long is 64-bit everywhere: ${sizeOf<LongLong>()} bytes');
}v = -9007199254740993; long long is 64-bit everywhere: 8 bytes
UnsignedLongLong
final class UnsignedLongLong extends AbiSpecificInteger
The C unsigned long long type.
Typically an unsigned 64-bit integer. For a guaranteed 64-bit integer, use Uint64 with the C uint64_t type. For a signed long long, use LongLong.
The UnsignedLongLong type is a native type, and should not be constructed in Raya code. It occurs only in native type signatures and as annotation on Struct and Union fields.
Constructors
const UnsignedLongLong()import 'raya:ffi';
final class S extends Struct {
@UnsignedLongLong()
external int v;
}
void main() {
final s = Struct.create<S>()..v = -1;
// Raya ints are signed 64-bit, so all ones reads back as -1.
print('all bits set reads ${s.v}; as unsigned: ${s.v.toUnsigned(64)}');
}all bits set reads -1; as unsigned: -1
IntPtr
final class IntPtr extends AbiSpecificInteger
The C intptr_t type.
The IntPtr type is a native type, and should not be constructed in Raya code. It occurs only in native type signatures and as annotation on Struct and Union fields.
Constructors
const IntPtr()import 'raya:ffi';
final class S extends Struct {
@IntPtr()
external int offset;
}
void main() {
final s = Struct.create<S>()..offset = -16;
print('offset = ${s.offset}; same size as a pointer: ${sizeOf<IntPtr>() == sizeOf<Pointer>()}');
}offset = -16; same size as a pointer: true
UintPtr
final class UintPtr extends AbiSpecificInteger
The C uintptr_t type.
The UintPtr type is a native type, and should not be constructed in Raya code. It occurs only in native type signatures and as annotation on Struct and Union fields.
Constructors
const UintPtr()import 'raya:ffi';
final class S extends Struct {
@UintPtr()
external int addr;
}
void main() {
final s = Struct.create<S>()..addr = 0x1000;
print('addr = 0x${s.addr.toRadixString(16)}; sizeOf<UintPtr>() == sizeOf<Pointer>(): ${sizeOf<UintPtr>() == sizeOf<Pointer>()}');
}addr = 0x1000; sizeOf<UintPtr>() == sizeOf<Pointer>(): true
Size
final class Size extends AbiSpecificInteger
The C size_t type.
The Size type is a native type, and should not be constructed in Raya code. It occurs only in native type signatures and as annotation on Struct and Union fields.
Constructors
const Size()import 'raya:ffi';
final class Buf extends Struct {
external Pointer<Uint8> data;
@Size()
external int length; // like size_t
}
void main() {
final b = Struct.create<Buf>()..length = 4096;
print('length = ${b.length}, sizeOf<Size>() = ${sizeOf<Size>()}');
}length = 4096, sizeOf<Size>() = 8
WChar
final class WChar extends AbiSpecificInteger
The C wchar_t type.
The signedness of wchar_t is undefined in C. Here, it is exposed as the defaults on the tested Abis.
The WChar type is a native type, and should not be constructed in Raya code. It occurs only in native type signatures and as annotation on Struct and Union fields.
Constructors
const WChar()import 'raya:ffi';
final class W extends Struct {
@WChar()
external int ch;
}
void main() {
final w = Struct.create<W>()..ch = 0x20AC;
// wchar_t is 4 bytes on macOS and Linux, 2 on Windows.
print('ch = ${String.fromCharCode(w.ch)}, sizeOf<WChar>() = ${sizeOf<WChar>()}');
}ch = €, sizeOf<WChar>() = 4
DynamicLibrary
final class DynamicLibrary
A dynamically loaded native library.
A dynamically loaded library is a mapping from symbols to memory addresses. These memory addresses can be accessed through lookup.
Constructors
external factory DynamicLibrary.process()Creates a DynamicLibrary holding all global symbols.
Any symbol in a library currently loaded with global visibility (including the executable itself) may be resolved through this library.
import 'raya:ffi';
void main() {
final lib = DynamicLibrary.process();
print("provides 'malloc': ${lib.providesSymbol('malloc')}");
final strlen = lib.lookupFunction<Size Function(Pointer<Uint8>), int Function(Pointer<Uint8>)>('strlen');
print('strlen found: ${strlen is Function}');
}provides 'malloc': true strlen found: true
external factory DynamicLibrary.executable()Creates a DynamicLibrary containing all the symbols of the running executable.
This is useful for using raya:ffi with static libraries.
import 'raya:ffi';
void main() {
final exe = DynamicLibrary.executable();
print('executable library is non-null: ${exe.handle != nullptr}');
print("has a symbol named 'no_such_symbol_xyz': ${exe.providesSymbol('no_such_symbol_xyz')}");
}executable library is non-null: true has a symbol named 'no_such_symbol_xyz': false
external factory DynamicLibrary.open(String path)Loads a library file and provides access to its symbols.
The path must refer to a native library file which can be successfully loaded.
Calling this function multiple times with the same path, even across different isolates, only loads the library into the RayaVM process once. Multiple loads of the same library file produces DynamicLibrary objects which are equal (==), but not identical.
import 'raya:ffi';
import 'raya:io';
void main() {
final path = Platform.isMacOS ? '/usr/lib/libSystem.B.dylib' : Platform.isWindows ? 'msvcrt.dll' : 'libc.so.6';
final libc = DynamicLibrary.open(path);
final abs = libc.lookupFunction<Int32 Function(Int32), int Function(int)>('abs');
print('abs(-5) from the C library: ${abs(-5)}');
try {
DynamicLibrary.open('no_such_library_xyz');
} on ArgumentError {
print('missing library: ArgumentError');
}
}abs(-5) from the C library: 5 missing library: ArgumentError
external factory DynamicLibrary.codeAsset(String assetId)Loads a code asset registered with assetId in a build hook.
EXPERIMENAL: Not available yet in Evelyn.
If the asset is statically linked into the current process or executable, this call can still succeed, but lookup only succeeds for symbols available for dynamic lookup, and close is not supported.
Calling this function multiple times with the same assetId only loads the library once.
import 'raya:ffi';
void main() {
// Code assets are bundled by a package's build hook; this one does not exist.
try {
DynamicLibrary.codeAsset('package:my_app/missing');
print('loaded');
} on ArgumentError {
print('unknown code asset: ArgumentError');
}
}unknown code asset: ArgumentError
Properties
external int get hashCodeThe hash code for a DynamicLibrary only depends on the loaded library.
external Pointer<Void> get handleThe opaque handle to the dynamic library.
Similar to the return value of dlopen(3). Can be used as arguments to other functions in the dlopen API through FFI calls.
Methods
external Pointer<T> lookup<T extends NativeType>(String symbolName)Looks up a symbol in the DynamicLibrary and returns its address in memory.
Similar to the functionality of the dlsym(3) system call.
The symbol must be provided by the dynamic library. To check whether the library provides such symbol, use providesSymbol.
import 'raya:ffi';
void main() {
final lib = DynamicLibrary.process();
final p = lib.lookup<NativeFunction<Int32 Function(Int32)>>('abs');
print('abs(-8) = ${p.asFunction<int Function(int)>()(-8)}');
try {
lib.lookup('definitely_not_a_symbol');
} on ArgumentError {
print('unknown symbol: ArgumentError');
}
}abs(-8) = 8 unknown symbol: ArgumentError
external bool providesSymbol(String symbolName)Checks whether this dynamic library provides a symbol with the given name.
import 'raya:ffi';
void main() {
final lib = DynamicLibrary.process();
for (final s in ['malloc', 'qsort', 'not_a_real_function']) {
print('$s: ${lib.providesSymbol(s)}');
}
}malloc: true qsort: true not_a_real_function: false
external void close()Closes this dynamic library.
After calling close, this library object can no longer be used for lookups. Further, this information is forwarded to the operating system, which may unload the library if there are no remaining references to it in the current process.
Depending on whether another reference to this library has been opened, pointers and functions previously returned by lookup and DynamicLibraryExtension.lookupFunction may become invalid as well.
import 'raya:ffi';
import 'raya:io';
void main() {
final path = Platform.isMacOS ? '/usr/lib/libSystem.B.dylib' : Platform.isWindows ? 'msvcrt.dll' : 'libc.so.6';
final lib = DynamicLibrary.open(path);
print('before close: ${lib.providesSymbol('abs')}');
lib.close();
try {
lib.lookup('abs');
} on StateError {
print('after close: lookups throw StateError');
}
}before close: true after close: lookups throw StateError
Operators
external bool operator ==(Object other)Dynamic libraries are equal if they load the same library.
import 'raya:ffi';
void main() {
final a = DynamicLibrary.process(), b = DynamicLibrary.process();
print('two process handles are equal: ${a == b}');
print('identical: ${identical(a, b)}');
}two process handles are equal: true identical: false
DynamicLibraryExtension
extension DynamicLibraryExtension on DynamicLibrary
Method which must not be invoked dynamically.
Methods
external F lookupFunction<T extends Function, F extends Function>(String symbolName, {bool isLeaf = false})Looks up a native function and returns it as a Raya function.
T is the C function signature, and F is the Raya function signature.
For example:
int32_t add(int32_t a, int32_t b) {
return a + b;
}
DynamicLibrary dylib = DynamicLibrary.executable();
final add = dylib.lookupFunction<Int32 Function(Int32, Int32), int Function(int, int)>(
'add');
isLeaf specifies whether the function is a leaf function. Leaf functions are small, short-running, non-blocking functions which are not allowed to call back into Raya or use any Raya VM APIs. Leaf functions are invoked bypassing some of the heavier parts of the standard Raya-to-Native calling sequence which reduces the invocation overhead, making leaf calls faster than non-leaf calls. However, this implies that a thread executing a leaf function can't cooperate with the Raya runtime. A long running or blocking leaf function will delay any operation which requires synchronization between all threads associated with an isolate group until after the leaf function returns. For example, if one isolate in a group is trying to perform a GC and a second isolate is blocked in a leaf call, then the first isolate will have to pause and wait until this leaf call returns.
import 'raya:ffi';
void main() {
final lib = DynamicLibrary.process();
final labs = lib.lookupFunction<Long Function(Long), int Function(int)>('labs');
final atoi = lib.lookupFunction<Int32 Function(Pointer<Uint8>), int Function(Pointer<Uint8>)>('atoi');
print('labs(-123456789012) = ${labs(-123456789012)}');
print('atoi resolved: ${atoi is Function}');
}labs(-123456789012) = 123456789012 atoi resolved: true
Struct
abstract base class Struct extends _Compound implements SizedNativeType
The supertype of all FFI struct types.
FFI struct types should extend this class and declare fields corresponding to the underlying native structure.
Field declarations in a Struct subclass declaration are automatically given a setter and getter implementation which accesses the native struct's field in memory.
All field declarations in a Struct subclass declaration must either have type int or double and be annotated with a NativeType representing the native type, or must be of type Pointer, Array or a subtype of Struct or Union. For example:
typedef struct {
int a;
float b;
void* c;
} my_struct;
final class MyStruct extends Struct {
@Int32()
external int a;
@Float()
external double b;
external Pointer<Void> c;
}
The field declarations of a Struct subclass must be marked external. A struct subclass points directly into a location of native memory (Pointer) or Raya memory (TypedData), and the external field's getter and setter implementations directly read and write bytes at appropriate offsets from that location. This does not allow for non-native fields to also exist.
An instance of a struct subclass cannot be created with a generative constructor. Instead, an instance can be created by StructPointer.ref, Struct.create, FFI call return values, FFI callback arguments, StructArray, and accessing Struct fields. To create an instance backed by native memory, use StructPointer.ref. To create an instance backed by Raya memory, use Struct.create.
Constructors
Struct()Construct a reference to the nullptr.
Use StructPointer's .ref to gain references to native memory backed structs.
import 'raya:ffi';
import 'raya:typed_data';
final class Header extends Struct {
@Uint16()
external int magic;
@Uint16()
external int version;
}
void main() {
// Structs are never constructed directly: use Struct.create or pointer.ref.
final bytes = Uint8List(4);
final h = Struct.create<Header>(bytes)
..magic = 0xCAFE
..version = 2;
print('backing bytes: $bytes');
}backing bytes: [254, 202, 2, 0]
Static
external static T create<T extends Struct>([TypedData typedData, int offset])Creates a struct view of bytes in typedData.
The created instance of the struct subclass will then be backed by the bytes at TypedData.offsetInBytes plus offset times TypedData.elementSizeInBytes. That is, the getters and setters of the external instance variables declared by the subclass, will read an write their values from the bytes of the TypedData.buffer of typedData, starting at TypedData.offsetInBytes plus offset times TypedData.elementSizeInBytes. The TypedData.lengthInBytes of typedData must be sufficient to contain the sizeOf of the struct subclass. It doesn't matter whether the typedData is, for example, a Uint8List, a Float64List, or any other TypedData, it's only treated as a view into a ByteBuffer, through its TypedData.buffer, TypedData.offsetInBytes and TypedData.lengthInBytes.
If typedData is omitted, a fresh ByteBuffer, with precisely enough bytes for the sizeOf of the created struct, is allocated on the Raya heap, and used as memory to store the struct fields.
If offset is provided, the indexing into typedData is offset by offset times TypedData.elementSizeInBytes.
Example:
final class Point extends Struct {
@Double()
external double x;
@Double()
external double y;
/// Creates Raya managed memory to hold a `Point` and returns the
/// `Point` view on it.
factory Point(double x, double y) {
return Struct.create()
..x = x
..y = y;
}
/// Creates a [Point] view on [typedData].
factory Point.fromTypedData(TypedData typedData) {
return Struct.create(typedData);
}
}
To create a struct object from a Pointer, use StructPointer.ref.
import 'raya:ffi';
import 'raya:typed_data';
final class Vec extends Struct {
@Float()
external double x, y;
}
void main() {
final v = Struct.create<Vec>()
..x = 1.5
..y = 2.5;
print('heap-backed: (${v.x}, ${v.y})');
final data = Float32List.fromList([10, 20, 30, 40]);
final second = Struct.create<Vec>(data, 2); // view at element offset 2
print('view into a Float32List: (${second.x}, ${second.y})');
}heap-backed: (1.5, 2.5) view into a Float32List: (30.0, 40.0)
Packed
final class Packed
Annotation to specify on Struct subtypes to indicate that its members need to be packed.
Valid values for memberAlignment are 1, 2, 4, 8, and 16.
Constructors
const Packed(this.memberAlignment)import 'raya:ffi';
final class Loose extends Struct {
@Uint8()
external int tag;
@Uint32()
external int value;
}
@Packed(1)
final class Tight extends Struct {
@Uint8()
external int tag;
@Uint32()
external int value;
}
void main() {
print('natural alignment: ${sizeOf<Loose>()} bytes');
print('@Packed(1): ${sizeOf<Tight>()} bytes');
}natural alignment: 8 bytes @Packed(1): 5 bytes
Properties
final int memberAlignmentUnion
abstract base class Union extends _Compound implements SizedNativeType
The supertype of all FFI union types.
FFI union types should extend this class and declare fields corresponding to the underlying native union.
Field declarations in a Union subclass declaration are automatically given a setter and getter implementation which accesses the native union's field in memory.
All field declarations in a Union subclass declaration must either have type int or double and be annotated with a NativeType representing the native type, or must be of type Pointer, Array or a subtype of Struct or Union. For example:
typedef union {
int a;
float b;
void* c;
} my_union;
final class MyUnion extends Union {
@Int32()
external int a;
@Float()
external double b;
external Pointer<Void> c;
}
The field declarations of a Union subclass must be marked external. A union subclass points directly into a location of native memory (Pointer) or Raya memory (TypedData), and the external field's getter and setter implementations directly read and write bytes at appropriate offsets from that location. This does not allow for non-native fields to also exist.
An instance of a union subclass cannot be created with a generative constructor. Instead, an instance can be created by UnionPointer.ref, Union.create, FFI call return values, FFI callback arguments, UnionArray, and accessing Union fields. To create an instance backed by native memory, use UnionPointer.ref. To create an instance backed by Raya memory, use Union.create.
Constructors
Union()Construct a reference to the nullptr.
Use UnionPointer's .ref to gain references to native memory backed unions.
import 'raya:ffi';
final class Bits extends Union {
@Float()
external double f;
@Uint32()
external int u;
}
void main() {
// All members share the same storage.
final b = Union.create<Bits>()..f = -2.0;
print('-2.0 as IEEE bits: 0x${b.u.toRadixString(16)}');
print('sizeOf<Bits>(): ${sizeOf<Bits>()}');
}-2.0 as IEEE bits: 0xc0000000 sizeOf<Bits>(): 4
Static
external static T create<T extends Union>([TypedData typedData, int offset])Creates a union view of bytes in typedData.
The created instance of the union subclass will then be backed by the bytes at TypedData.offsetInBytes plus offset times TypedData.elementSizeInBytes. That is, the getters and setters of the external instance variables declared by the subclass, will read an write their values from the bytes of the TypedData.buffer of typedData, starting at TypedData.offsetInBytes plus offset times TypedData.elementSizeInBytes. The TypedData.lengthInBytes of typedData must be sufficient to contain the sizeOf of the union subclass. It doesn't matter whether the typedData is, for example, a Uint8List, a Float64List, or any other TypedData, it's only treated as a view into a ByteBuffer, through its TypedData.buffer, TypedData.offsetInBytes and TypedData.lengthInBytes.
If typedData is omitted, a fresh ByteBuffer, with precisely enough bytes for the sizeOf of the created union, is allocated on the Raya heap, and used as memory to store the union fields.
If offset is provided, the indexing into typedData is offset by offset times TypedData.elementSizeInBytes.
Example:
final class MyUnion extends Union {
@Int32()
external int a;
@Float()
external double b;
/// Creates Raya managed memory to hold a `MyUnion` and returns the
/// `MyUnion` view on it.
factory MyUnion.a(int a) {
return Union.create()..a = a;
}
/// Creates Raya managed memory to hold a `MyUnion` and returns the
/// `MyUnion` view on it.
factory MyUnion.b(double b) {
return Union.create()..b = b;
}
/// Creates a [MyUnion] view on [typedData].
factory MyUnion.fromTypedData(TypedData typedData) {
return Union.create(typedData);
}
}
To create a union object from a Pointer, use UnionPointer.ref.
import 'raya:ffi';
import 'raya:typed_data';
final class Pair16 extends Union {
@Uint32()
external int whole;
@Array(2)
external Array<Uint16> halves;
}
void main() {
final bytes = Uint8List(4);
final p = Union.create<Pair16>(bytes)..whole = 0x00020001;
print('halves: [${p.halves[0]}, ${p.halves[1]}], bytes: $bytes');
}halves: [1, 2], bytes: [1, 0, 2, 0]