Alexander Theißen Alexander Theißen - 2 months ago 80x
iOS Question

Casting between different UnsafePointer<T> in swift

I am trying to use a C-Api from swift. As an example the C-Api goes this ways:

void doThingsOnRawData(const unsigned char* data);

Swift converts this to:

void doThingsOnRawData(UnsafePointer<UInt8>);

Now I want to pass the data from an NSData to the function. NSData.byte returns the type:


  1. Is this some kind of void* type?

  2. At least swift won't accept it as an
    . What do I do to cast this?


struct UnsafePointer<T> has a constructor

/// Convert from a UnsafePointer of a different type.
/// This is a fundamentally unsafe conversion.
init<U>(_ from: UnsafePointer<U>)

which you can use here


You can even omit the generic type because it is inferred from the context:


Update for Swift 3: As of Xcode 8 beta 6, you cannot convert directly between different unsafe pointers anymore.

For data: NSData, data.bytes is a UnsafeRawPointer which can be converted to UnsafePointer<UInt8> with assumingMemoryBound:

doThingsOnRawData(data.bytes.assumingMemoryBound(to: UInt8.self))

For data: Data it is even simpler:

data.withUnsafeBytes { doThingsOnRawData($0) }