Reputation: 3889
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<()>
Is this some kind of void* type?
At least swift won't accept it as an UnsafePointer<UInt8>
. What do I do to cast this?
Upvotes: 27
Views: 16376
Reputation: 539685
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) }
Upvotes: 40