Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting between different UnsafePointer<T> in swift

Tags:

macos

ios

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?

like image 596
Alexander Theißen Avatar asked Aug 18 '14 09:08

Alexander Theißen


1 Answers

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) }
like image 74
Martin R Avatar answered Oct 20 '22 05:10

Martin R