[swift-dev] `withUnsafePointer` mutates `self`
Joe Groff
jgroff at apple.com
Tue Dec 15 17:03:48 CST 2015
> On Dec 15, 2015, at 8:12 AM, Ryan Lovelett via swift-dev <swift-dev at swift.org> wrote:
>
> 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.
Yeah, it seems to me like a reasonable refinement for 'withUnsafePointer' to take an immutable parameter. Since this is a stdlib API change, you should suggest that on swift-evolution.
-Joe
More information about the swift-dev
mailing list