Alexander Theißen Alexander Theißen - 3 months ago 125
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:

UnsafePointer<()>



  1. Is this some kind of void* type?

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


Answer

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

doThingsOnRawData(UnsafePointer<UInt8>(data.bytes))

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

doThingsOnRawData(UnsafePointer(data.bytes))

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) }