allocate<T extends NativeType> function

Pointer<T> allocate <T extends NativeType>(
  1. {int count: 1}
)

Allocates memory on the native heap.

For POSIX-based systems, this uses malloc. On Windows, it uses HeapAlloc against the default public heap. Allocation of either element size or count of 0 is undefined.

Throws an ArgumentError on failure to allocate.

Implementation

Pointer<T> allocate<T extends NativeType>({int count = 1}) {
  final int totalSize = count * sizeOf<T>();
  Pointer<T> result;
  if (Platform.isWindows) {
    result = winHeapAlloc(processHeap, /*flags=*/ 0, totalSize).cast();
  } else {
    result = posixMalloc(totalSize).cast();
  }
  if (result.address == 0) {
    throw ArgumentError("Could not allocate $totalSize bytes.");
  }
  return result;
}