在不同的UnsafePointer< T>之间进行转换在迅速 [英] Casting between different UnsafePointer<T> in swift
问题描述
我正试图从swift中使用C-Api。作为一个例子,C-Api采用这种方式:
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将其转换为:
Swift converts this to:
void doThingsOnRawData(UnsafePointer<UInt8>);
现在我想将数据从NSData传递给函数。 NSData.byte返回类型:
Now I want to pass the data from an NSData to the function. NSData.byte returns the type:
UnsafePointer<()>
-
这是某种类型的void *类型吗?
Is this some kind of void* type?
至少swift不会接受它作为 UnsafePointer< UInt8>
。我该怎么办呢?
At least swift won't accept it as an UnsafePointer<UInt8>
. What do I do to cast this?
推荐答案
struct UnsafePointer< T>
有一个构造函数
/// Convert from a UnsafePointer of a different type.
///
/// This is a fundamentally unsafe conversion.
init<U>(_ from: UnsafePointer<U>)
您可以使用这里
doThingsOnRawData(UnsafePointer<UInt8>(data.bytes))
您甚至可以省略泛型类型,因为它是从上下文中推断出来的:
You can even omit the generic type because it is inferred from the context:
doThingsOnRawData(UnsafePointer(data.bytes))
Swift 3的更新:从Xcode 8 beta 6开始,您不能再在不同的不安全指针之间直接转换
。
Update for Swift 3: As of Xcode 8 beta 6, you cannot convert directly between different unsafe pointers anymore.
对于数据: NSData
, data.bytes
是一个 UnsafeRawPointer
,可以将
转换为 UnsafePointer< UInt8>
with assumeMemoryBound
:
For data: NSData
, data.bytes
is a UnsafeRawPointer
which can
be converted to UnsafePointer<UInt8>
with assumingMemoryBound
:
doThingsOnRawData(data.bytes.assumingMemoryBound(to: UInt8.self))
对于数据:数据
它甚至更简单:
data.withUnsafeBytes { doThingsOnRawData($0) }
这篇关于在不同的UnsafePointer< T>之间进行转换在迅速的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!