Swift get value from UnsafeMutablePointer<Void> using UnsafePointer<String>

寵の児 提交于 2019-12-03 07:50:59

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<Void>(Unmanaged<NSString>.passRetained(str).toOpaque())
    bar(ptr)
}

func bar(v:UnsafePointer<Void>) {
    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<Void>) {
    println("notified")
    let str = Unmanaged<NSString>.fromOpaque(COpaquePointer(v)).takeRetainedValue()
    println("info: \(str)")
}


foo()

println("started")

dispatch_main()
  • Unmanaged<NSString>.passRetained(str) increments the retain count.
  • Unmanaged<NSString>.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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!