How to use CPointer in Kotlin/Native
Asked Answered
E

0

6

I cannot find out how to use CPointer in Kotlin/Native; In my iOS source set, I need to build the Kotlin equivalent of the following Object-c code (only including relevant parts of the code):

    //Object-C copyItemAtPath
    NSError* error=nil;
    [[NSFileManager defaultManager]copyItemAtPath:srcPath toPath:dstPath error:&error ];
    if (error!=nil) {
        NSLog(@"%@", error);
    }

But in Kotlin/Native,I dont know how to transfrom the code;I tried the following kotlin code and failed;

        //I try to read error info 
        val errorPtr = allocPointerTo<ObjCObjectVar<NSError?>>()
        NSFileManager.defaultManager.copyItemAtPath("source", target,errorPtr.value)
        Napier.e("[KNDraftCopy]${errorPtr.pointed?.value?.localizedDescription}")//null
        Napier.e("[KNDraftCopy]${errorPtr.pointed?.value}")//null
        Napier.e("[KNDraftCopy]${errorPtr.pointed}")//null
        Napier.e("[KNDraftCopy]${errorPtr}")//kotlinx.cinterop.NativePointed@d063d3a8

I am a fish of C Code,there is the question of me: How to transform my Obj-C code to kotlin/native? Is my way right?(The result is invalid.)

// the function definition
fun copyItemAtPath(srcPath: kotlin.String, toPath: kotlin.String, error:CPointer<ObjCObjectVar<platform.Foundation.NSError?>>?)
Ecumenism answered 3/8, 2020 at 3:36 Comment(2)
Please try something like this: ``` memScoped { val errorPtr: ObjCObjectVar<NSError?> = alloc<ObjCObjectVar<NSError?>>() NSFileManager.defaultManager.copyItemAtPath("source", target, errorPtr.ptr) println(errorPtr.value) } ```Libertinage
thank u much,the ptr works by this wayEcumenism

© 2022 - 2024 — McMap. All rights reserved.