C interoperability: CPointer of a stack variable

I’m trying to write a JNI implementation of some function that is called from JVM. That function at some point needs to convert a JVM String to a Kotlin String. This means that I have to call the GetStringUTFChars function so that the JVM will return me a pointer to the UTF8 string.

This function has a C interface defined as:

const char * GetStringUTFChars(JNIEnv *env, jstring string, jboolean *isCopy);

The third argument points to a jboolean (which is a UByte) that will be changed by the JVM; so I need to pass an adress of UByte to this function.

I know that I can allocate memory by using memScoped+alloc, and currently this solution works:

    memScoped {
        val copiedPtr = alloc<UByte>(0U)
        val jvmString = native.GetStringUTFChars!!(env, path, copiedPtr.ptr)
        if (jvmString != null) {
            val s = jvmString.toKString()
            println("(copied=${copiedPtr.value}) $s")
            native.ReleaseStringUTFChars!!(env, path, jvmString)
        }
    }

However, this seems to perform a malloc-style call inside alloc<>, and will call free() on the end of the scope (or is it wrong?). It seems to be a pretty high overkill. Is there any possibility of just declaring an UByte, or allocating it on the stack instead of on the heap, and getting the CPointer<UByte> of that stack-allocated variable?

2 Likes