从Swift创建非托管<cfstring>

时间:2015-12-04 16:32:09

标签: swift memory memory-management interop automatic-ref-counting

从Swift 2开始,可以在没有中间包装的情况下从Swift调用带有C回调的C函数。

许多C事件处理API遵循您首先创建上下文的模式:

struct Context {
    CFIndex version;
    void *info;
    CFAllocatorRetainCallBack retain;
    CFAllocatorReleaseCallBack release;
    CFAllocatorCopyDescriptionCallBack copyDescription;
}

然后在注册我们的回调时将上下文传递给C API。收到事件时,info指针随事件一起传递给回调函数,允许我们恢复上下文状态(因为C函数不允许捕获状态)。

我想正确创建这样的上下文,包括retainreleasecopyDescription回调。

对于copyDescription,签名为

typealias CFAllocatorCopyDescriptionCallBack = 
    (UnsafePointer<Void>) -> Unmanaged<CFString>!

如何从Swift创建Unmanaged<CFString>!实例,即如何将Swift字符串对象从ARC内存模型中转移到外部管理的模型中?

1 个答案:

答案 0 :(得分:0)

见问题评论。

let string = Unmanaged.passRetained("description")