[swift-dev] `withUnsafePointer` mutates `self`

Ryan Lovelett swift-dev at ryan.lovelett.me
Tue Dec 15 10:12:55 CST 2015


I've been playing around with a Swift wrapper for the FFmpeg C libraries
(e.g., libavutil, libavcodec, libavformat, etc...). While providing some
extensions to some of the core C structures I've run into something that
doesn't feel quite right to me.

Before I provide a discussion here is a Gist [0] that I hope illustrates
the problem.

When inside of a Swift function declaration if I take `self` and send it
to `withUnsafePointer` Swift requires the function to mark the function
as `mutating`. This surprised me. Thanks to Swift being open source (🎉)
I was able to go look at the implementation of `withUnsafePointer` [1].
And I'm no longer surprised that its required by the compiler; the
definition marks the argument as `inout`.

However, this seems wrong to me. In the "Pointers" section of "Using
Swift with Cocoa and Objective-C (Swift 2.1)" [2] it says that `cost
Type *` (pointer to a constant value) is equivalent to
`UnsafePointer<Type>`. My understanding of C says that `const Type *`
means that the instance of `Type` that the pointer points to cannot be
modified. This corresponds with my understanding of the difference
between `UnsafePointer<Type>` and `UnsafeMutablePointer<Type>`.

Therefore, from my perspective I feel like there is a bug here. It also
seems that marking the `arg` of `withUnsafePointer` to `var` instead of
`inout` would allow it to compile and would more closely model the
`UnsafePointer`. I'm still new to all this and I don't want to make a
fool of myself. So I'd rather ask here before I move forward and file a
bug and MR.

[0] https://gist.github.com/RLovelett/e5ee7f173877bb8475dc
[1]
https://github.com/apple/swift/blob/8d9ef80304d7b36e13619ea50e6e76f3ec9221ba/stdlib/public/core/LifetimeManager.swift#L93-L102
[2]
https://developer.apple.com/library/ios/documentation/Swift/Conceptual/BuildingCocoaApps/InteractingWithCAPIs.html#//apple_ref/doc/uid/TP40014216-CH8-ID17


More information about the swift-dev mailing list