darkmoon_uk
10/27/2020, 6:39 AMstruct -[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.svyatoslav.scherbina
10/29/2020, 12:00 PMto retrieve/unwrap the original struct type from itPlease 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.Stefan Thaler
04/26/2021, 11:41 AMsvyatoslav.scherbina
04/27/2021, 8:19 AMfun 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:
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())
Stefan Thaler
04/27/2021, 4:33 PM