6

I'm using a C library in my Swift project, and one of functions requires a UnsafePointer<UnsafePointer<UInt8>?>! as an in-out argument where I should pass my data. But the problem is that I have this data in UnsafeMutablePointer<UnsafeMutablePointer<UInt8>?>! type.

My question is - What is the most efficient and easiest way to convert UnsafeMutablePointer to UnsafePointer in Swift 3? Those pointers are not much different "on paper" and they shouldn't be much different from technical context, but I couldn't find valuable information on that topic.

Any help would be appreciated. Thanks

Eugene Alexeev
  • 1,152
  • 12
  • 32
  • How is that function declared in C? – Martin R Feb 21 '18 at 20:46
  • Maybe use `unsafeBitCast`? – Cristik Feb 21 '18 at 20:46
  • @MartinR Hello and thank you for your answer! I Think it's not important but here: `int av_image_alloc(uint8_t *pointers[4], int linesizes[4], int w, int h, enum AVPixelFormat pix_fmt, int align);` – Eugene Alexeev Feb 23 '18 at 07:26
  • @Cristik Hello! I don't know if it's an efficient solution but thanks for you suggestion! – Eugene Alexeev Feb 23 '18 at 07:27
  • 1
    @EugeneAlexeev it's 100% efficient, as it runs in `O(1)`, however not sure if the compiler or runtime will let you to properly cast. And it's unsafe, as the name says, as you can end up with unexpected results if you improperly use it. – Cristik Feb 23 '18 at 07:28
  • @EugeneAlexeev: Well, I asked because I wondered about the "in-out argument". And that C function would be imported to Swift as `public func av_image_alloc(_ pointers: UnsafeMutablePointer?>!, ...)` with mutable pointers, so I wonder why you have to convert your arguments to `UnsafePointer`. – Martin R Feb 23 '18 at 07:37

1 Answers1

9

UnsafePointers can be initialized with an UnsafeMutablePointer

// Any UnsafeMutablePointer with capacity one
let ump = UnsafeMutablePointer<Any>.allocate(capacity: 1)
// `up` now contains an UnsafePointer initialized with `ump`
var up = UnsafePointer(ump)
Phil Dukhov
  • 67,741
  • 15
  • 184
  • 220
Boris
  • 11,373
  • 2
  • 33
  • 35