allocate<T extends NativeType> method
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.
Implementation
@override
Pointer<T> allocate<T extends NativeType>(int byteCount, {int? alignment}) {
final Pointer<T> result;
if (Platform.isWindows) {
result = CoTaskMemAlloc(byteCount).cast();
} else {
result = posixMalloc(byteCount).cast();
}
if (result.address == 0) {
throw ArgumentError('Failed to allocate $byteCount bytes.');
}
if (!LeakTracker.enabled) return result;
final stack = formatStackTrace(StackTrace.current.toString());
LeakTracker._registerAllocation(
.new(
address: result.address,
size: byteCount,
type: '$T',
stack: stack,
timestamp: .now(),
),
);
return result;
}