allocAligned<T extends Struct> method

Pointer<T> allocAligned<T extends Struct>(
  1. int size,
  2. int alignment, {
  3. int count = 1,
})

Allocate aligned memory for custom sized native types

  • size: The size of the memory to allocate
  • alignment: The alignment boundary
  • count: The number of elements to allocate (default is 1) Returns a pointer to the allocated memory

Implementation

Pointer<T> allocAligned<T extends Struct>(
  int size,
  int alignment, {
  int count = 1,
}) {
  // Calculate the required size with space for alignment
  final baseSize = count * size;
  final totalSize = baseSize + alignment - 1;

  // Allocate memory with extra space for alignment
  final ptr = calloc<Uint8>(totalSize);

  // Calculate the aligned address
  final addr = ptr.address;
  final alignedAddr = (addr + alignment - 1) & ~(alignment - 1);

  // Convert back to pointer
  return Pointer.fromAddress(alignedAddr).cast<T>();
}