I feel dumb - what is best way to get C string al...
# kotlin-native
m
I feel dumb - what is best way to get C string allocated in nativeHeap from Kotlin String?
Copy code
/** Provides a complete description of a font where one is needed.  */
open class Font(
    family: String? = null,
    size: Double = 0.0,
    weight: uiTextWeight = uiTextWeightNormal,
    italic: uiTextItalic = uiTextItalicNormal,
    stretch: uiTextStretch = uiTextStretchNormal
) : Disposable<uiFontDescriptor>(
    alloc = nativeHeap.alloc<uiFontDescriptor>().ptr
) {
    init {
        with(ptr.pointed) {
            Family = family?.cstr.rawPtr //.getPointer(nativeHeap)
            Size = size
            Weight = weight
            Italic = italic
            Stretch = stretch
        }
    }

    override fun clear() {
        ptr.pointed.Family?.let { nativeHeap.free(it) }
    }

    override fun free() {
        clear()
        nativeHeap.free(ptr)
    }
}
Family
is C string = so how to initialize it in Kotlin wrapper?
j
Have you looked into ArenaBase?
m
Recomended in INTEROP.md way does not work:
val cString = kotlinString.cstr.getPointer(nativeHeap)
Error: type mismatch Required: AutofreeScope Found: nativeHeap
o
somewhat imperfect but this shall work
fun mycstring(s: String) = s.cstr.place(nativeHeap.allocArray(s.length * 4))
s
I find using
Arena
the most idiomatic approach for this case. You can create one along with object instance and dispose in
clear
. See also https://github.com/JetBrains/kotlin-native/blob/master/samples/videoplayer/src/videoPlayerMain/kotlin/Disposable.kt The arena object can be used in
getPointer
.