Can't get native-lib callback to not segfault or fail with runtime assert

Hi there, I am new to Koltin native (but used it on the JVM before) and have a hard time figuring out, how to correctly implement a callback from jackaudio.

Here is what I tried:

private lateinit var client: CPointer<jack_client_t>
private lateinit var inputPort: CPointer<jack_port_t>
private var position = nativeHeap.alloc<jack_position_t>()
private var event = nativeHeap.alloc<jack_midi_event_t>()

fun main() {
                       Print JACK MIDI
        This program creates a JACK MIDI port and will
          print in the console all input it recieves

                     Press Enter to abort

    try {
        val readLine = readLine()
    catch(e: Exception) {
    finally {

fun startJackMidiCallback() {
    client = requireNotNull(jack_client_open("cykuit-pro", JackNullOption, null)) { "Jack server not running?" }
    inputPort = requireNotNull(jack_port_register(client, "midi_in", JACK_DEFAULT_MIDI_TYPE, JackPortIsInput.toULong(), 0))

    val callback = staticCFunction(
        fun(nframes: jack_nframes_t, _: COpaquePointer?): Int {
            return process(nframes)
    jack_set_process_callback(client, callback, null)

    if (jack_activate(client) != 0) {
        throw IllegalStateException("Cannot activate client")

fun process(nframes: jack_nframes_t): Int {

    val portBuf = jack_port_get_buffer(inputPort, nframes)
    val transport = jack_transport_query(client, position.ptr)

    for (i in 0 until jack_midi_get_event_count(portBuf).toInt()) {
        jack_midi_event_get(event.ptr, portBuf, i.toUInt())
        val frame = position.frame
        val subFrame = event.time
        val size = event.size
        val data0 = event.buffer?.get(0) ?: 0
        val data1 = event.buffer?.get(1) ?: 0
        val data2 = event.buffer?.get(2) ?: 0
        println("Event: $i")
            "Frame $frame SubFrame#: $subFrame \tMessage ($size):\t" +

    return 0

As soon as I try to print some of the received data, I get either a segfault or

/mnt/agent/work/f01984a9f5203417/runtime/src/main/cpp/Memory.cpp:1581: runtime assert: add ref for reclaimed object

I can’t really pinpoint under what circumstances, I get which. I tried to slam .freeze() here and there to no avail. I first tried to use memScoped in the process() function, but this segfaults even immediately when calling jack_transport_query.

So I must be doing something wrong, but I have a hard time finding information regarding this kind of problems…

Thanks in advance for any pointers!