Is array index access `[]` only available for `CPo...
# kotlin-native
j
Is array index access
[]
only available for
CPointer<ByteVar>
? The docs seem to imply it should be possible for any
CPointer<T>
, but I only see the extension available for
CPointer<ByteVar>
(the docs show
CPointer<BytePtr>
in the example code). Do I have to
reinterpret<ByteVar>()
in order to iterate an array of a different pointer type?
l
I believe it's available for primitives, not structs
Make sure if you reinterpret that you pay attention to the size of the elements, as that will change the indexing
j
Thanks, I made these extensions for array access of struct arrays and conversion to kotlin list:
Copy code
inline operator fun <reified T : CStructVar> CPointer<T>?.plus(index: Int): CPointer<T>? =
    interpretCPointer(this.rawValue + index * sizeOf<T>())

inline operator fun <reified T : CStructVar> CPointer<T>.get(index: Int): T =
    (this + index)!!.pointed

inline fun <reified T : CStructVar, R> CPointer<T>.toList(
    size: Int,
    transform: (CPointer<T>) -> R
): List<R> {
    val array = this
    return buildList(size) {
        repeat(size) { i ->
            add(transform(array[i].ptr))
        }
    }
}