Search code examples
ckotlinkotlin-native

Passing pointer to unsigned string to bindings generated by kotlin cinterop


I'm trying to use C-library with Kotlin-native C-interop, and I need to pass to a C-function some string. C-function has signature (omitting the details):

typedef unsigned char GByte;

void someFunFromC(GByte* data); 

The same functions from Kotlin can be called like:

someFunctionFromC(data: kotlinx.cinterop.CValuesRef<libmylib.GByteVar /* = kotlinx.cinterop.UByteVarOf<libmylib.GByte /* = kotlin.UByte */> */>?)

So, how described in Kotlin documentation (https://kotlinlang.org/docs/tutorials/native/mapping-strings-from-c.html) I tried to use it this way:

val kotlinString = "this is a Kotlin String"
someFunctionFromC(kotlinString.cstr)

and get:

Required : CValuesRef<GByteVar /* = UByteVarOf<GByte /* = UByte */> */>?
Found : CValues<ByteVar /* = ByteVarOf<Byte  /*>

It happened because I need to pass in C-function not char* cstring , but unsigned char* cstring

Solution that I found to resolve it:

kotlinString.toUtf8().toUByteArray().usePinned { kString ->
    someFunctionFromC(kString.adressOf(0))
}

It work, but doesn’t look well. Maybe someone can suggest a better way?


Solution

  • You can try to use kotlinString.cstr as? CValuesRef<GByteVar>.