我如何在Swift中处理CFSocketCallbackType.datacallback



所有文档和示例说,如果将插座的CFSocketCallBack标注赋予.dataCallback作为其第二个参数(callbackType),则意味着可以将第四个(data)施加到CFData对象上包含从插座预读的所有数据。

但是,当我尝试这样做时,它会失败:

private func myCallout(socket: CFSocket?,
                       callBackType: CFSocketCallBackType,
                       address: CFData?,
                       callBackTypeMetaData: UnsafeRawPointer?,
                       info: UnsafeMutableRawPointer?) -> Void {
    // Behavior inferred from Developer
    // https://developer.apple.com/documentation/corefoundation/cfsocketcallback
    guard
        let info = info,
        let socket = socket
        else {
        return assertionFailure("Socket may have gone out of scope before response")
    }
    // <REDACTED>

    if callBackType == .dataCallBack {
        guard let data = callBackTypeMetaData?.load(as: CFData.self) else {
            return assertionFailure("Data Callback's metadata was not a CFData object")
        }
        foo(data as Data) // Crashes here
    }
    // <REDACTED>
}

我得到的崩溃是:

Thread 1: EXC_BREAKPOINT (code=EXC_I386_BPT, subcode=0x0).

在调试器中,当我键入此内容时:

(lldb) po callBackTypeMetaData!.load(as: CFData.self)

它只是打印一个指针地址(也很高,也只有两个重要的0 s)。但是,当我键入此内容时:

(lldb) po callBackTypeMetaData!.load(as: CFData.self) as Data

它打印此:

error: Execution was interrupted, reason: EXC_BREAKPOINT (code=EXC_I386_BPT, subcode=0x0).
The process has been returned to the state before expression evaluation.

所以我似乎真的不是CFData,但是它足够近,看起来与表面上的相似之处,直到某种东西实际上试图读取它。

那么,这里发生了什么,我的数据在哪里,我该解决此问题?

data = callBackTypeMetaData!.load(as: CFData.self)

callBackTypeMetaData!指向的内存位置读取CFData指针。您想要的是"重新诠释"原始指针作为CFData(或NSData)指针:

if callBackType == .dataCallBack {
    if let rawPointer = callBackTypeMetaData  {
        let data = Unmanaged<NSData>.fromOpaque(rawPointer).takeUnretainedValue() as Data
        // ...
    }
}

相关内容

  • 没有找到相关文章

最新更新