[swift-users] Can't use unsafe pointer from second thread?

Robert Nikander robert.nikander at icloud.com
Sun Jun 18 08:23:58 CDT 2017


Hi,

I’m porting some C to Swift and I need to pass a Swift instance through a `void *` (ie, UnsafeMutableRawPointer). It works, in one thread, but when a second thread accesses the exact same pointer, it fails with memory errors like EXC_BAD_ACCESS

The code below could be pasted into an AppDelegate.swift in a new single view iOS project. 

Anyone know what’s going on here? The second call to `tryUsingUnsafePointer`, in the new thread, crashes.

Rob


class PointerTest {
    
    let str = "Hello"
    
    init() { print("PointerTest.init") }    
    deinit { print("PointerTest.deinit") }
    
    func start() {
        var mSelf = self
        let unsafePtr = UnsafeMutableRawPointer(&mSelf)
        tryUsingUnsafePointer(unsafePtr)
        print("Passing unsafe pointer to another thread: \(unsafePtr)")        
        Thread.detachNewThread {
            tryUsingUnsafePointer(unsafePtr)
        }
    }
}

func tryUsingUnsafePointer(_ ptr: UnsafeMutableRawPointer) {
    print("Using unsafe pointer:")
    let typedPtr = ptr.assumingMemoryBound(to: PointerTest.self)
    // let typedPtr = ptr.bindMemory(to: PointerTest.self, capacity: 1)
    print("   typedPtr: \(typedPtr)")
    let obj = typedPtr.pointee
    print("   obj.str: \(obj.str)")  // Memory error happening here, or sometimes line above
}


@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?
    var ptrTest: PointerTest?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

        ptrTest = PointerTest()
        ptrTest?.start()

        return true
    }

[...]




-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20170618/4523fb89/attachment.html>


More information about the swift-users mailing list