`struct -[ObjC-to-Kotlin]-> CValue<struct&gt...
# kotlin-native
d
struct -[ObjC-to-Kotlin]-> CValue<struct> -[Kotlin-to-ObjC]-> struct
☝️ 🤔 Is this is gap in K/N interop? On iOS, I'm handling some Obj-C struct types in my business logic. These are represented in Kotlin-land as a
CValue<MyStruct>
as per interop documentation. Now I'm passing those values back to the UI layer, they comes back out of Kotlin code into Swift/Obj-C. At this point they are still seen as
CValue<MyStruct>
with no apparent means, to retrieve/unwrap the original struct type from it... is this not possible? The documentation is lacking when it comes to explaining how to bridge structs in this direction.
s
to retrieve/unwrap the original struct type from it
Please allocate the struct in Swift/Obj-C (stack allocation is enough) and then use https://kotlinlang.org/api/latest/jvm/stdlib/kotlinx.cinterop/-c-values/place.html to copy the
CValue
contents to the specified location. Also, if you receive the struct in Swift/Obj-C through as a parameter when overriding a method of Kotlin class or interface, then you can switch parameter type from struct value to struct pointer in Kotlin.
s
Could you provide an example?
s
Sure! Depending on your case, example1 or example2 might help: Kotlin:
Copy code
fun example1(resultPtr: CPointer<MyStruct>) {
    val cValue = cValue<MyStruct> { x = 42 }
    cValue.place(resultPtr)
}

interface Example2 {
    fun example2(ptr: CPointer<MyStruct>)
}

fun callExample2(e: Example2) {
    val cValue = cValue<MyStruct> { x = 43 }
    memScoped {
        e.example2(cValue.ptr)
    }
}
Swift:
Copy code
var myStruct = MyStruct()
TestKt.example1(resultPtr: &myStruct)
print("Got struct from Kotlin in Swift 1: \(myStruct)")

class Example2Impl : Example2 {
    func example2(ptr: UnsafeMutableRawPointer) {
        print("Got struct from Kotlin in Swift 2: \(ptr.load(as: MyStruct.self))")
    }
}

TestKt.callExample2(e: Example2Impl())
s
Thanks a lot 🙂
👍 1