import com.dshatz.kni.buffers.ByteBuffer
// commonMain
@JniCall
expect fun fillBuffer(buffer: ByteBuffer): String
// Native
actual fun fillBuffer(buffer: ByteBuffer): String {
val bytes = Random.nextBytes(buffer.capacity.toInt())
buffer.put(bytes)
return bytes.toHexString()
}
Call from commonMain:
// commonMain
import com.dshatz.kni.buffers.allocateBuffer
val buffer = allocateBuffer(1024)
val filledHex = fillBuffer(buffer) // call native
val contents = buffer.readToByteArray(0, 1024) // read contents
// filledHex == contents.toHexString()
Buffer lifetime on native
A ByteBuffer received as a parameter of a @JniCall function, or of the constructor of a class with @JniCall functions, is only borrowed: it is invalidated when the function or constructor returns, and using it afterwards throws BufferReleasedException.
This applies to suspend functions too: the buffer stays valid until the suspend function completes, even though that is after the underlying JNI call has returned. The JVM buffer is kept alive for that whole time, even if the caller no longer references it.
To keep the buffer, call retain() during the call. You then own it and must call release() when done:
@JniCall
actual fun keep(buffer: ByteBuffer) {
stored = buffer.retain()
}
Storing a buffer received in a constructor works the same way:
actual class Holder actual constructor(buffer: ByteBuffer) : AutoCloseable {
private val buffer = buffer.retain()
actual override fun close() {
buffer.release()
}
}
Sensitive data
wipe() overwrites the whole buffer with zeros. To wipe automatically on release(), allocate with wipeOnRelease:
val buffer = allocateBuffer(64, wipeOnRelease = true)
encodeToByteBuffer encodes a string as UTF-8 directly into a new buffer, optionally with a trailing zero byte for C strings, without an intermediate ByteArray:
Native code can only access direct buffers. Passing a buffer that wraps a heap java.nio.ByteBuffer (e.g. java.nio.ByteBuffer.allocate(n).toCommonByteBuffer()) to native code throws IllegalArgumentException. Use allocateBuffer or java.nio.ByteBuffer.allocateDirect instead.
Converting
JVM
val jvmBuffer = java.nio.ByteBuffer.allocateDirect(1024)
val buffer = jvmBuffer.toCommonByteBuffer()
buffer.jvmBuffer == jvmBuffer
Native
On native, this is a wrapper around a pointer.
Wrap ByteArray
val bytes = Random.nextBytes(100)
val buffer = ByteBuffer.wrapArray(bytes)
Wrap address in memScoped
// wrap a memory address
memScoped {
val arr = allocArray<ByteVar>(1024)
val buffer = ByteBuffer.wrapAddressMemScope(this, arr, 1024)
}
JS/Wasm
val buffer = allocateBuffer(1024)
buffer.asInt8Array()
buffer.toBlob()