java.nio.ByteBuffer
While passing java.nio.ByteBuffer is not possible because such type does not exist on Native, the buffers module provides an efficient wrapper.
Use com.dshatz.kni.buffers.ByteBuffer in function signatures:
Setup
Add the dependency:
implementation("com.dshatz.kni:buffers:2.1.0")
Buffers module provides a convenient and efficient wrapper around byte buffers for all platforms.
Allocating / releasing
val buffer: ByteBuffer = allocateBuffer(1024)
buffer.release()
Reading / writing
val bytes: ByteArray = Random.nextBytes(buffer.capacity.toInt())
buffer.write(bytes)
val bytes: ByteArray = buffer.readToByteArray(0, 1024)
Properties
The following properties are available on the ByteBuffer:
Property | Platforms |
|---|---|
| All |
| JVM/Android |
| Native |
Passing to JNI
See the general guide: ➡️ Calling Native code from JVM
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()
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()
Last modified: 23 April 2026