Krystian
09/12/2023, 8:58 PMint TextCopy(char *dst, const char *src);
dst
would be an array of char in C I believe. K/N wants a CValuesRef<ByteVar>
What's the best way to pass that through? I was thinking of ByteArray.toCValues()
but something tells me no..Jeff Lockhart
09/12/2023, 9:07 PMsrc
coming from and what do you need to do with dst
?
Mostly it depends if you need to hang on to a reference to dst
long term, or if its usage is within a specific scope, how you want to allocate its memory.Krystian
09/12/2023, 9:19 PMKrystian
09/12/2023, 9:20 PMJeff Lockhart
09/12/2023, 9:24 PMString
, a CharArray
, a CPointer<u_charVar>
, something else?Jeff Lockhart
09/12/2023, 9:38 PMmemScoped {
val dst: CPointer<u_charVar> = allocArray(length)
val result = TextCopy(dst, src)
}
But dst
will only be allocated until the end of the memScoped
block. This is why I asked what ultimately you need to do with dst
. If you turn it into a Kotlin object (String
or CharArray
), it will then be managed by the Kotlin GC. But as long as it's a C variable you allocated, you need to manage the memory manually.Krystian
09/12/2023, 9:50 PMJeff Lockhart
09/12/2023, 10:15 PMit would return a String actuallyDo you mean a Kotlin
String
object?
Why is it you need to copy the string with this C function? What is the src
input string? Is there a reason you wouldn't just copy it to a Kotlin String
directly?Krystian
09/13/2023, 5:04 AMJeff Lockhart
09/13/2023, 5:20 AMmemScoped { ... }
, you can allocate with nativeHeap
, but you need to manually free the memory when you're done with it.
As for working with strings, you can normally call toKString()
on a native C string pointer to convert to a Kotlin String
.Krystian
09/13/2023, 5:52 AMJeff Lockhart
09/13/2023, 6:24 AMchar *
pointer to a C function from Kotlin, you have to allocate that memory natively somehow, in one of the ways described in the link above. GC won't automatically clean up natively allocated memory. It will depend on your use case whether that memory can be scoped with memScoped
because you only need it in a scope directly at the call site to the C function or if you intend to keep the native memory around for longer, in which case, you'd allocate with nativeHeap
and need to take care of calling free on it when you're done with it.