With Swift's Unmanaged, how do passRetained and passUnretained differ when an object travels through a C callback's void pointer?
answer
- ARC stops at a raw pointer
- an unbalanced retain travels along
- balance it exactly once
- take, not just read
basics
~20 sUnmanaged.passRetained adds one strong reference that travels with the pointer, so the object survives until the callback balances it with takeRetainedValue or release. passUnretained adds nothing: something else must keep the object alive, or the callback reads freed memory.
solid answer
~40 sA C API that stores a `void *` context cannot hold a Swift strong reference, so ARC stops counting at that boundary and `Unmanaged` makes you do the counting. `Unmanaged.passRetained(obj).toOpaque()` performs an unbalanced retain — the standard library warns the instance "will leak if nothing eventually balances the retain" — so use it when the C side keeps the pointer beyond the current call, and balance it exactly once, typically with `Unmanaged<T>.fromOpaque(ptr).takeRetainedValue()` in the final callback, or `release()`. `passUnretained` changes no counts; it is right only when another strong reference provably outlives every callback, such as an owner that also tears down the registration. Miss the balance and the object leaks; skip the retain and the callback dereferences a freed instance — undefined behaviour that can even appear to work.
code
swift · 26 linesfinal class Upload {
let id: Int
init(id: Int) { self.id = id }
deinit { print("Upload \(id) freed") }
}
typealias Callback = @convention(c) (UnsafeMutableRawPointer?) -> Void
// Stands in for a C library that stores a callback and a void * context.
var pending: [(Callback, UnsafeMutableRawPointer?)] = []
func register(_ callback: Callback, _ context: UnsafeMutableRawPointer?) {
pending.append((callback, context))
}
func start() {
let upload = Upload(id: 7)
let context = Unmanaged.passRetained(upload).toOpaque() // +1 travels with the pointer
register({ context in
let upload = Unmanaged<Upload>.fromOpaque(context!).takeRetainedValue() // balances it
print("finished upload \(upload.id)")
}, context)
} // the local reference ends; the +1 keeps it alive
start()
print("start() returned")
for (callback, context) in pending { callback(context) }go deeper
Recall that a raw pointer does not keep a Swift object alive, and that Unmanaged is how you hand an object to C code explicitly.
Explain which Unmanaged calls add a count, which consume one, and which change nothing, and pair them for a one-shot callback.
Choose retained or unretained per callback shape, and spot the leak, use-after-free and double-release patterns in review before they ship.
Keep Unmanaged conversions confined to a thin boundary layer with documented ownership, so the rest of the codebase stays ordinary ARC code.
## Why ARC stops at a raw pointer ARC counts **strong references** that the compiler can see: variables, properties, collection elements, captures. A C API that takes a callback and an untyped context — `void *` in C, `UnsafeMutableRawPointer?` in Swift — stores a plain address. The compiler cannot retain through it, so a Swift object handed over that way has no owner on the C side. **`Unmanaged<Instance>`** is the standard-library type for this boundary. Its own documentation says that when you use it, "you become partially responsible for keeping the object alive". ## The operations and what they do to the count | Operation | Effect on the reference count | |---|---| | `Unmanaged.passRetained(_:)` | +1, an **unbalanced retain** | | `Unmanaged.passUnretained(_:)` | none | | `toOpaque()` / `Unmanaged.fromOpaque(_:)` | none — "This operation does not change reference counts." | | `takeRetainedValue()` | returns a strong reference and consumes the unbalanced retain | | `takeUnretainedValue()` | returns a strong reference, leaves any unbalanced retain in place | | `retain()` / `release()` | +1 / −1 by hand | The doc comments state the intent of each pair: `passRetained` is for an API you know expects the object "at +1"; `passUnretained` for one that expects it "at +0"; `takeRetainedValue` when "you're responsible for releasing the result"; `takeUnretainedValue` when "you're not responsible". ## Choosing the right pair 1. **One-shot callback** (a completion called exactly once): `passRetained` when registering, `takeRetainedValue()` inside the callback. The retain travels with the pointer and is consumed where the pointer is last used. 2. **Repeating callback** (fired many times until you unregister): `passRetained` at registration, `takeUnretainedValue()` on each call, and one `release()` — or `takeRetainedValue()` — when the registration is torn down. 3. **Context owned elsewhere**: `passUnretained` only when some other strong reference is guaranteed to outlive every callback, for example an owner object that keeps the context alive and cancels the registration in its own teardown. ## What goes wrong - **Leak.** `passRetained` balanced with `takeUnretainedValue()` keeps the +1 forever. Built with Swift 6.4, the example with that change prints "finished upload 7" and never prints "Upload 7 freed". - **Use after free.** `passUnretained` with no other owner lets the instance die when the registering function returns. In a Swift 6.4 run of that variant, "Upload 7 freed" printed before the callback — which then printed the correct id from freed memory. That apparent success is why the bug ships; the behaviour is undefined. - **Double release.** Calling `takeRetainedValue()` in a callback that fires twice consumes the single +1 twice; the second release frees an object that is still referenced elsewhere, or one that is already gone. ## Where the balancing call belongs The +1 has to be released by code that is guaranteed to run, and one tempting place is not: - **Not in the object's own `deinit`.** If an object registers itself with `Unmanaged.passRetained(self)`, that retain keeps its count above zero, so its `deinit` cannot run while the registration stands. A plan to release the context in `deinit` therefore never fires; the object leaks. - **In an explicit teardown.** Balance the retain in a `stop()`, `cancel()` or `invalidate()` method that unregisters from the C side first and then calls `release()`, or in the C library's own "done" or "destroy" callback when it offers one. - **Exactly once.** If both the final callback and a teardown method could release, guard it so only one does; a second `release()` is an over-release. ## Related tools and limits - Core Foundation functions imported without ownership information return `Unmanaged` values, and the same rule applies: `takeRetainedValue()` for a result you own, `takeUnretainedValue()` for one you don't. - The standard library's `_withUnsafeGuaranteedRef` lets the optimizer skip a retain while another reference is pinned, but the Swift optimization notes call it "not a public API" that "will go away in the future"; pin the owner with `withExtendedLifetime(_:_:)` and use the public methods. - Keep the conversion at the boundary: turn the context back into a strong reference at the top of the callback and use that reference, so the rest of the code is ordinary ARC-managed Swift. ## The review checklist For every `toOpaque()` in a pull request, ask who owns the +1, where it is consumed, and how many times the callback can fire. If the answer to the first question is "nobody", the code is relying on luck.
- For a callback that fires many times, which take method do you call on each invocation?`takeUnretainedValue()`: it hands you a strong reference for the call without consuming the retain made by `passRetained` at registration. Balance that retain exactly once, with `release()` or `takeRetainedValue()`, when the registration is torn down.
- Does Unmanaged.fromOpaque(_:) retain the object it reconstructs?No. Its documentation says "This operation does not change reference counts", and the same holds for `toOpaque()`. Only `passRetained` and `retain()` add a count; `takeRetainedValue()` and `release()` remove one.
passRetained is checking a coat and taking a ticket: the cloakroom keeps the coat until someone redeems the ticket once with takeRetainedValue. passUnretained is leaving the coat on a chair and hoping it is still there when you come back.
- toOpaque() retains the object, so the pointer keeps it alive
- passUnretained is safe because the object is referenced somewhere
- takeUnretainedValue releases the extra retain after the callback
- If the callback prints the right value, ownership is correct
- takeRetainedValue is fine in a callback that fires repeatedly