How to convert a List or Array to C Array in Kotlin/Native

20 views Asked by At

Given an array Array<VkDeviceQueueCreateInfo> I want to convert it to a C Array of C values (or pointer to the first item), i. e. VkDeviceQueueCreateInfo*.

This is where I'm getting a type mismatch (obviously): type mismatch

How do I convert this Array<VkDeviceQueueCreateInfo> to CPointer<VkDeviceQueueCreateInfo>? I don't want to create an array of pointers.

1

There are 1 answers

0
xdevs23 On

I created this extension function that allocates a new array on the given NativePlacement and then copies every single item from the source collection to the newly allocated array and returns that array.

inline fun <reified T : CVariable> Collection<T>.toCArray(np: NativePlacement = nativeHeap): CArrayPointer<T> {
    val typeSize = sizeOf<T>()
    val array = np.allocArray<T>(this.size)
    forEachIndexed { index, item ->
        memcpy(
            interpretPointed<T>(array.rawValue + index * typeSize).ptr,
            item.ptr,
            typeSize.toULong()
        )
    }
    return array
}

It might not be that great of a solution but is the best I was able to come up with.