How can I convert `List<T>` (where `T` is a ...
# kotlin-native
a
How can I convert
List<T>
(where
T
is a
CStructVar
) to
CValuesRef<T>
?
list2cvalues.kt
o
what is the
points
type in C?
a
the C function signature is
Copy code
void GeneratedExternalFunction(Vector2 *points)
and Vector2 is
Copy code
typedef struct Vector2 {
    float x;
    float y;
} Vector2;
Kotlin generates these types:
Copy code
public external expect fun GeneratedExternalFunction
(points: kotlinx.cinterop.CValuesRef<cinterop.Vector2>?): kotlin.Unit { /* compiled code */ }

public final expect class Vector2 public constructor(rawPtr: kotlinx.cinterop.NativePtr /* = kotlin.native.internal.NativePtr */) : kotlinx.cinterop.CStructVar {
    public expect companion object : kotlinx.cinterop.CStructVar.Type {
    }

    public expect final var x: kotlin.Float /* compiled code */

    public expect final var y: kotlin.Float /* compiled code */
}
o
you will need to do smth like this:
Copy code
val vectorValues: List<CValue<Vector2>> = vectors.map { it.readValue() }
val array = allocArray<T>(elements.size)
vectorValues.forEachIndexed { index, element -> element.place(array.get(index).ptr) }
GeneratedExternalFunction(array)
a
thanks! This seems to compile
I did a bit of refactoring, do you think this helper function works the same?
Copy code
inline fun <reified T : CStructVar> NativePlacement.allocArrayOfStructs(
  values: List<T>,
): CPointer<T> = allocArray(values.size) { index ->
  values[index].readValue().place(ptr)
}
o
yeah, looks like