Hey folks! We're trying to see if we can write a W...
# kotlin-native
l
Hey folks! We're trying to see if we can write a Window manager with Kotlin/Native, but starting out with it, we're hitting some issues we cannot seem to figure out. this is working c code:
Copy code
xcb_connection = create_xcb_connection();
xcb_setup = xcb_get_setup(xcb_connection);
xcb_screen_iterator = xcb_setup_roots_iterator(xcb_setup);
xcb_screen = xcb_screen_iterator.data;
xcb_root = xcb_screen->root;
and this is the kotlin counterpart to the c code above, but it unfortunately crashes with a null-pointer,
Copy code
import kotlinx.cinterop.*
import xcb.*

fun main() {
    val connection = xcb_connect(null, null)
    val xcb_setup = xcb_get_setup(connection)!!
    val xcb_screen_iterator = xcb_setup_roots_iterator(xcb_setup)

    // val xcb_screen = xcb_screen_iterator.placeTo(scope).pointed.data!!

    // This !! crashes, indicating that the data value here is null. in the equivalent C code shown above, 
    // This exact same value is _not_ null however, which makes us think
    // that we are wrongly using the Kotlin/Native C interop somehow.
    val xcb_screen = xcb_screen_iterator.useContents { data }!!

    val xcb_root = xcb_screen.pointed.root
    
    println("okidoki")
}
As described in the comment, we're getting a null value on
xcb_screen_iterator.useContents { data }
, which - as far as we understand - should be equivalent to the C code given above, which does work. Any help would be appreciated. LIkely, we're just failing to understand how to use kotlin native's C interop
This is how we define the interop stuff, in case it in any way matters or helps
Copy code
package = xcb
headers = xcb/xcb.h xcb/xcb_event.h xcb/xproto.h xcb/randr.h xcb/shape.h
headerFilter = xcb/*
compilerOpts = -I/usr/include
linkerOpts = -L/usr/lib -lxcb -lxcb-randr
n
The use of the !! operator is a code smell. Instead of doing that make use of the ?:, and ? operators, along with null checks, eg:
Copy code
val xcb_setup = xcb_get_setup(connection)
if (xcb_setup == null) {
  fprintf(stderr, "Cannot setup xcb")
  exitProcess(-1)
}
Alternatively you could do something like this:
Copy code
fun fetchXcbSetup(conn: CPointer<xcb_connect>?): CPointer<xcb_setup>? = xcb_get_setup(conn) ?: throw IllegalStateException("Cannot setup xcb")
l
Yea I know, don't worry. The
!!
Was just used to make the null value more obvious. Turns out, the issue was on our side tho, and we where missing something in how to interact with xcb