Is there a straightforward way to convert Array&lt...
# kotlin-native
n
Is there a straightforward way to convert Array<String> to CValuesRef<CPointerVar<ByteVar>>? IntelliJ is showing the following type in the Quick Documentation: CValuesRef<CPointerVar<gcharVar /* = ByteVarOf<gchar /* = Byte */> /> / = CPointerVarOf<CPointer<ByteVarOf<gchar /* = Byte */>>> */>? I'm wondering if I have correctly deciphered the type (into a human readable version) presented by IntelliJ.
s
Actually, yes! It seems there's a function specifically for this called
Array<String>.toCStringArray(autofreeScope: AutofreeScope)
. It returns a
CPointer<CPointerVar<ByteVar>>
, which is exactly what you want. You just need to provide it a MemScope, which you can use
memScoped
for.
👍 3
n
Initially I used a boilerplate type solution (manually allocate a CArrayPointer of a fixed size in a mem scope, and set elements in the array via iteration, before passing the CArrayPointer to the C function, eg gtk_scale_button_set_icons), eg:
Copy code
// ...    
fun changeIcons(icons: Array<String>): Unit = memScoped {
        val tmp = allocArray<CPointerVar<ByteVar>>(icons.size)
        @Suppress("ReplaceRangeToWithUntil")
        (0..(icons.size - 1)).forEach { pos -> tmp[pos] = icons[pos].cstr.ptr }
        gtk_scale_button_set_icons(gtkScaleButtonPtr, tmp)
    }
@serebit - Your solution looks much better than what I have come up with 😄 .
The example using Campbell's solution now looks like the following:
Copy code
// ...    
fun changeIcons(icons: Array<String>): Unit = memScoped {
        gtk_scale_button_set_icons(gtkScaleButtonPtr, icons.toCStringArray(this))
    }
👍 1