Swift get value from UnsafeMutablePointer using UnsafePointer

前端 未结 1 596
忘掉有多难
忘掉有多难 2021-02-09 18:40

I am trying to pass contextInfo of typeUnsafeMutablePointer to UISaveVideoAtPathToSavedPhotosAlbum and use it in the callback

1条回答
  •  南旧
    南旧 (楼主)
    2021-02-09 19:29

    As discussed in OP comments, testStr has already been freed.

    Is there any way to force the retaining of a variable that has been created in a function? Then release it later?

    It's not impossible, but I don't know this is the best way to do that.

    Anyway, try this with Playground or OS X "Command Line Tool" template:

    import Foundation
    
    func foo() {
        var str:NSString = "Hello World"
        let ptr = UnsafePointer(Unmanaged.passRetained(str).toOpaque())
        bar(ptr)
    }
    
    func bar(v:UnsafePointer) {
        let at = dispatch_time(
            DISPATCH_TIME_NOW,
            Int64(2.0 * Double(NSEC_PER_SEC))
        )
        dispatch_after(at, dispatch_get_main_queue()) {
            baz(v)
        }
    }
    
    func baz(v:UnsafePointer) {
        println("notified")
        let str = Unmanaged.fromOpaque(COpaquePointer(v)).takeRetainedValue()
        println("info: \(str)")
    }
    
    
    foo()
    
    println("started")
    
    dispatch_main()
    
    • Unmanaged.passRetained(str) increments the retain count.
    • Unmanaged.fromOpaque(...).takeRetainedValue() decrements it, and extract the object.

    I think, using pure Swift String is impossible. because String is struct and is allocated in stack memory. Maybe the buffer of it is allocated in heap, but we cannot access it directly.

    0 讨论(0)
提交回复
热议问题