On my adventures with working on a small 2d game f...
# kotlin-native
k
On my adventures with working on a small 2d game framework with SDL2 cinterop I decided to experiment and I have a question regarding these two computed properties:
Copy code
val Texture.width: Int
    get() = memScoped {
        val w = alloc<IntVar>()
        SDL_QueryTexture(this@width, null, null, w.ptr, null)
        w.value
    }

val Texture.width: Int
    get() {
        val byte = ByteArray(Int.SIZE_BYTES)
        SDL_QueryTexture(this@width, null, null, byte.usePinned { it.addressOf(0).reinterpret() }, null)
        return byte.usePinned {
            it.addressOf(0).pointed.value.toInt()
        }
    }
Both are working fine and as intended, they return the width size of the texture, however. I'm curious about using usePinned example and is it actually safe to use? At this point the value is fully managed by Kotlin GC, isn't it? Am I safe to assume it's okay for me to do this?
a
I'm no expert, but the use of
memScoped {}
seems okay to me. I'd be cautious about using
usePinned {}
like that. I'd try and do all operations within a single scope, and use an IntVar rather than a ByteArray, something like this:
Copy code
val Texture.width: Int
  get() {
    return memScoped { 
      alloc<IntVar>().usePinned { intVar ->
        SDL_QueryTexture(this@width, null, null, intVar.get().ptr, null)
        intVar.get().value
      }
    }
  }
Does that seem like it would work for you?
k
The reason why I wanted to play with this is to actually avoid alloc for the sake of knowledge. Now that curiosity is driving me to find out if its actually safe to use usePinned. In the end memScoped does similar as it automatically disposed at the end of scope, but wouldnt usePinned do exactly the same once GC releases the ByteArray when it also is out of scope?
a
yeah, using a ByteArray instead of alloc+memScoped is probably fine. Personally I'd prefer it because I'd want to avoid the reinterpret magic. I suspect the most important thing is to use a single
usePinned {}
. Your original code will usually work, but there might be an edge case where the memory location moves between
usePinned {}
invocations.
👍 1
k
Yeah I'm going to experiment with it and be wary regardless. I've read around about using usePinned here and there, but I'm genuinely curious what can be done to break it. And yeah... reinterpret magic is real cause I've got more than a size of a texture at this point. Want a rectangle? Ngl this sort of messing about is what brings me joy from Kotlin
a
yeah for sure, I quite like the lower level aspect of Kotlin/Native compared to JVM