Swift2, Call swift function in CFSocketCallBack - EXEC_BAD_ACCESS

1.1k Views Asked by At

I'm trying to write a socket server app for Mac OSX with Xcode:7.2.1 in Swift2.1.1. referring to CocoaEcho sample code. But I cannot call a swift function in the socketCallBack function.
My code is here. I'm passing the self based on the answer at Swift 2 - UnsafeMutablePointer to object. And I think the part of the code is working ok.

class myServer: NSObject {

  // sockets
  private var socketipv4: CFSocket!
  private var socketipv6: CFSocket!

  // Connections
  var connections = Set<SPFConnection>()

  func start(address: String) -> Bool {

    var sockCtxt = CFSocketContext(version: 0, info: nil, retain: nil, release: nil, copyDescription: nil)
    sockCtxt.info = UnsafeMutablePointer(unsafeAddressOf(self))

    // create socket with CFSocketCreate
    socketipv4 = CFSocketCreate(
        kCFAllocatorDefault,
        PF_INET,
        SOCK_STREAM,
        IPPROTO_TCP,
        kCFSocketAutomaticallyReenableAcceptCallBack,
        socketCallBack,
        &sockCtxt)

    // ipv4
    var sin = sockaddr_in()  // = initStruct()
    let server_addr_size = socklen_t(INET_ADDRSTRLEN)
    sin.sin_len = UInt8(server_addr_size)
    sin.sin_family = sa_family_t(AF_INET)
    sin.sin_port = UInt16(9999).bigEndian
    sin.sin_addr.s_addr = inet_addr(address)

    let sinData = NSData(bytes: &sin, length: sizeof(sockaddr_in))
    let ptr = UnsafePointer<UInt8>(sinData.bytes)

    let sincfd = CFDataCreate(kCFAllocatorDefault, ptr, sizeof(sockaddr_in))

    let ipv4SocketError: CFSocketError = CFSocketSetAddress(socketipv4, sincfd)
    switch ipv4SocketError {
    case .Success:
        print("ipv4 Success")
    default:
        print("ipv4 error = \(ipv4SocketError.rawValue)")
        return false
    }

    let socketSource = CFSocketCreateRunLoopSource(kCFAllocatorDefault, socketipv4, 0)
    CFRunLoopAddSource(CFRunLoopGetCurrent(), socketSource, kCFRunLoopDefaultMode)

    return true
  }

  // CFSocket call back
  var socketCallBack : @convention(c)(CFSocket!, CFSocketCallBackType, CFData!, UnsafePointer<Void>, UnsafeMutablePointer<Void>) -> Void = {
    (socketRef, callbackType, address, data, info) in

    print("acceptConnection callback-ed") // \(socketRef), \(callbackType), \(address), \(data),\(info)")

    var tempData: CFSocketNativeHandle = 0
    var anNSData:NSData = NSData(bytes: data, length: sizeofValue(data))
    anNSData.getBytes(&tempData, length: sizeof(CFSocketNativeHandle))

    var tempAry = [UnsafeMutablePointer<Void>]()
    tempAry.append(info)
    if callbackType == CFSocketCallBackType.AcceptCallBack {
        let server = unsafeBitCast(info, myServer.self)
        // **** EXEC_BAD_ACCESS, code=2 ***** //
        server.acceptConnection(tempData)
    } else {
        print("callbacktype = \(callbackType.rawValue)")
    }
  }


  func acceptConnection(data: CFSocketNativeHandle) {
    print("acceptConnection called")
    var readStream: Unmanaged<CFReadStream>?
    var writeStream: Unmanaged<CFWriteStream>?

    CFStreamCreatePairWithSocket(kCFAllocatorDefault, data, &readStream, &writeStream)
    if readStream != nil && writeStream != nil {
        CFReadStreamSetProperty(readStream!.takeUnretainedValue(), kCFStreamPropertyShouldCloseNativeSocket, kCFBooleanTrue)
        CFWriteStreamSetProperty(writeStream!.takeUnretainedValue(), kCFStreamPropertyShouldCloseNativeSocket, kCFBooleanTrue)

        let connection = SPFConnection()
        connection.inputStream = readStream!.takeRetainedValue()
        connection.outputStream = writeStream!.takeRetainedValue()

        if connection.open() {
            connections.insert(connection)
        }
    }
  }
}

I'm getting EXEC_BAD_ACCESS code=2 at the code server.acceptConnection(tempData).
Debugger shows same pointer for both info and server, which should mean info(self) is properly assigned to server. But EXEC_BAD_ACCESS seems to mean self is no longer available. I'm struggling to find a solution. If anyone could give me any advise, it'd be very much appreciated. Thanks in advance for your help.

1

There are 1 best solutions below

4
On

I'll admit I don't know much about using these lower level C conventions, but since the callback function is part of your class, can't just say self.acceptConnection(tempData)?