如何将我的 swift class 转换为 UnsafePointer,例如 objective-c 中的 __bridge

How do I convert my swift class to an UnsafePointer like the __bridge in objective-c

我正在尝试实现 swift 到 SecureTransport C 库的桥梁。我 'think' 我可以将任何东西作为连接传递,只要我知道如何在我的 sslReadCallback/sslWriteCallback 实现中从中读取内容。这是我正在使用的假设。当我查看 SSLConnectionRef 的定义时似乎就是这种情况:

/* Opaque reference to an I/O connection (socket, endpoint, etc.) */
public typealias SSLConnectionRef = UnsafePointer<Void>

所以我只需要将我的 class 变成 UnsafePointer。不幸的是编译器不喜欢我的尝试。谁能给我点提示吗?

func startSSLProcess()
{
    self.sslContext = SSLCreateContext(kCFAllocatorDefault, SSLProtocolSide.ClientSide, SSLConnectionType.StreamType)
    if let sslContext = self.sslContext
    {
        SSLSetIOFuncs(sslContext, sslReadCallback, sslWriteCallback)
        SSLSetConnection(sslContext, UnsafePointer(self)) // <-- error
        SSLSetSessionOption(sslContext, SSLSessionOption.BreakOnClientAuth, true)
        SSLHandshake(sslContext)
    }
}

在 GCDAsyncSocket 中,它是这样做的:

status = SSLSetConnection(sslContext, (__bridge SSLConnectionRef)self);

SubZeroGCDAsyncSocket *asyncSocket = (__bridge SubZeroGCDAsyncSocket *)connection;

..展开。 swift 相当于什么?

非常感谢!

答案在这里:

所以现在我执行以下操作:

func startSSLProcess()
{
    self.sslContext = SSLCreateContext(kCFAllocatorDefault, SSLProtocolSide.ClientSide, SSLConnectionType.StreamType)
    if let sslContext = self.sslContext
    {
        SSLSetIOFuncs(sslContext, sslReadCallback, sslWriteCallback)
        SSLSetConnection(sslContext, UnsafePointer(Unmanaged.passUnretained(self).toOpaque()))
        SSLSetSessionOption(sslContext, SSLSessionOption.BreakOnClientAuth, true)
        SSLHandshake(sslContext)
    }
}

然后我这样打开:

    let transportWrapper:SecureTransportWrapper = Unmanaged<SecureTransportWrapper>.fromOpaque(COpaquePointer(connection)).takeUnretainedValue()

用您自己的类型替换 SecureTransportWrapper。