# kotlin-native


11/29/2023, 9:56 AM
I am calling a library via cinterop. I manage some of the allocations via memScoped. Everything works fine. Still, since I am new to this calling model, I want to make sure that allocations are handled correctly. libvips uses gobject to manage some of its memory. Is there a good way to connect the gobject machinery to kotlins machinery for freeing memory? Here is how my code looks like right now
Copy code
fun createImageFastPath(
    targetWidth: Int,
    sourceImageBytes: ByteArray,
    format: String,
    desiredQuality: Int?
): ByteArray {
    return memScoped {
        val imageBuffer = sourceImageBytes.refTo(0)
        val length = sourceImageBytes.size.toULong()
        val thumbnail = allocPointerTo<VipsImage>()
        val objectsToUnref = mutableListOf<CPointerVar<VipsImage>>()

        vips_thumbnail_buffer(imageBuffer, length, thumbnail.ptr, targetWidth, "linear", true, null)

        val bufferOut = allocPointerTo<ByteVar>()
        val sizeOut = alloc<size_tVar>()

        val quality = desiredQuality ?: 70
        val (size, buffer) = saveToFile(thumbnail, bufferOut, sizeOut, format, quality)

        val imageBytes = ByteArray(size)
        memcpy(imageBytes.refTo(0), buffer, size.toULong())

        objectsToUnref.forEach {

also, is running valgrind relevant on a kotlin/native binary? I guess at least the memory management in the C library will be correctly tracked by valgrind