Skip to content

2. MemoryPointer

Nikita Shtengauer edited this page Oct 16, 2024 · 1 revision

MemoryPointer contains a reference to the allocated memory in context. Memory can be allocated on the GPU, so it should not be accessed often.

Due to some platform limitations, only the following data types are supported:

  • Float (4 bytes)
  • Int (4 bytes)
  • Byte

Allocation

To allocate some amount of empty memory, you need to call the following methods in context:

// 100 floats
val memoryF = context.allocFloats(100)

// 100 integers
val memoryI = context.allocInts(100)

// 100 bytes
val memoryB = context.allocBytes(100)

Wrapping

Often you need to use existing data from RAM. To do this, you can wrap it:

// Float
val arrayF = floatArrayOf(1f, 2f, 3f, 4f, 5f)
val memoryF = context.wrapFloats(arrayF)

// Int
val arrayI = intArrayOf(1, 2, 3, 4, 5)
val memoryI = context.wrapInts(arrayI)

// Byte
val arrayB = byteArrayOf(1, 2, 3, 4, 5)
val memoryB = context.wrapBytes(arrayB)

A copy is created, so changes are not reflected in any arrays

Writing

Once a MemoryPointer has been created, you can update some of its data in any time.

The following fields are specified:

  • Array
  • Length
  • Source offset
  • Destination offset
val newData = floatArray(0f, 1f, 2f, 3f, 4f, 5f, 6f)

// Writes all elements
memoryF.write(newData)

// Will write '0f, 1f, 2f'
memoryF.write(newData, 3)

// Will write '0f, 1f, 2f, 3f' relative to the 2nd index of the memory
memoryF.write(newData, 4, 0, 2)

// Will write '3f, 4f, 5f' relative to the 4th index of the memory
memoryF.write(newData, 2, 3, 4)

Reading

When operations are performed on memory, you most likely need to get the result.

To do this, you can read the MemoryPointer, specifying the following parameters:

  • Length
  • Offset
// Reads all elements
val result1 = memoryF.read()

// Reads first 3 elements
val result2 = memoryF.read(3)

// Reads 3 elements relative to the 6th index
val result3 = memoryF.read(3, 6)

Deallocation

When memory is no longer needed, call the dealloc() method.

memoryF.dealloc()

Clone this wiki locally