Monday, August 14, 2017

Swift.Unmanaged

Mike Ash:

In order to work with C APIs, we sometimes need to convert Swift object references to and from raw pointers. […] You can do this with unsafeBitCast, although I strongly recommend against it.

[…]

To create the Unmanaged value, use fromOpaque. Unlike passRetained and passUnretained, you must specify the generic type for Unmanaged when using fromOpaque so that the compiler knows which class you're expecting to receive.

Once you have the Unmanaged value, you can get a reference out of it. Using takeRetainedValue will perform an unbalanced release, which will balance an unbalanced retain previously performed with passRetained, or by C code which confers ownership on your code. Using takeUnretainedValue will obtain the object reference without performing any retain or release.

[…]

To retrieve a reference from C into Swift code, you create an Unmanaged value from the raw pointer, then take a reference from it. There are two ways to take a reference: one which consumes an unbalanced retain, and once which performs no memory management.

Previously: Swift 3.0 Unsafe World.

Comments RSS · Twitter

Leave a Comment