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?
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) }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With