1

Why? Always crash, when i using unsafeBitCast function, please refer to following code and an error message:

Code: "let obj: MyController = unsafeBitCast(context, MyController.self)"

Error: Thread11: EXEC_BAD_ACCESS(code=1, address=0x20)

public class MyController: NSObject {

    public override init() {
        super.init()
        registerEventHandler()
    }

    let callback: @convention(c) (Int ,UnsafeMutablePointer<Void>) -> Void = { event, context in

        //Always crash, when i deal with context using unsafeBitCast
        let obj: MyController = unsafeBitCast(context, MyController.self)
    }

    public func registerEventHandler() {
        let selfObj = unsafeBitCast(self, UnsafeMutablePointer<Void>.self)

        //call C function
        RegisterEventHandler(callback, selfObj)
    }
}
Bartłomiej Semańczyk
  • 56,735
  • 45
  • 213
  • 327
CocoaUser
  • 1,321
  • 1
  • 14
  • 28
  • hm ... is hard to see, what actually happened in your code, but your idea should work.class C { var i = 1 func foo() { print("foo") } } let c = C() c.i = 10 // this cast class C as UnsafeMutablePointer let c1 = unsafeBitCast(c, UnsafeMutablePointer.self) // this cast UnsafeMutablePointer as C let c2: C = unsafeBitCast(c1, C.self) c2.foo() c2.i // 10 – user3441734 Dec 07 '15 at 15:56
  • Compare http://stackoverflow.com/questions/30786883/swift-2-unsafemutablepointervoid-to-object for a similar issue. – Is it guaranteed that `MyController` won't get deallocated while the callback is still registered? – Martin R Dec 07 '15 at 19:14

0 Answers0