2 回答
TA贡献1725条经验 获得超7个赞
struct S {
var i: Int = 10
}
var first = S()
func foo(contextPtr: UnsafeMutablePointer<Void>){
let pS = UnsafeMutablePointer<S>(contextPtr)
pS.memory.i = 100
}
print(first.i) // 10
foo(&first)
print(first.i) // 100
如果我们需要传递为UnsafeMutablePointer self到异步函数
import XCPlayground
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
import Foundation
// can be struct, class ...
class C {
let queue = dispatch_queue_create("test", DISPATCH_QUEUE_CONCURRENT)
var s: String = ""
func foo() {
var c = self
dispatch_async(queue) { () -> Void in
f(&c)
}
}
}
func f(pV: UnsafeMutablePointer<Void>) {
let pC = UnsafeMutablePointer<C>(pV)
sleep(1)
print(pC.memory.s)
}
var c1: C? = C()
c1!.s = "C1"
c1!.foo() // C1
var c2: C? = C()
c2!.s = "C2"
c2!.foo() // C2
c1 = nil
c2 = nil
print("test")
- 2 回答
- 0 关注
- 509 浏览
添加回答
举报