NSData(bytes:length :)如何将[Byte]转换为UnsafePointer< Void>在Swift? [英] How does NSData(bytes:length:) convert [Byte] to UnsafePointer<Void> in Swift?
问题描述
在Swift中使用原始数据我遇到了一些我不明白的问题。
NSData 有一个构造函数:
init(bytes:UnsafePointer< Void> ;, length:Int)
$ b b
其中第一个字节参数显然是 UnsafePointer 类型。
但是,如果我通过 [Byte] >对象到这个构造函数,不仅编译器不会抱怨,而且它工作正常。
但是如果我尝试转换 [Byte] 到 UnsafePointer
这是如何工作的?
例如(你可以在Playgrounds试试):
let buffer:[Byte] = [0x00,0xff]
let data = NSData(bytes:buffer,length:buffer.count)没有错误
data.description
var指针:UnsafePointer< Void>
//注释此行以避免编译器错误
指针=缓冲区//错误
我知道我可以做
UnsafePointer< Void>(缓冲区)
/ pre>
但我的问题是,NSData构造函数隐式地做什么,我不必这样做。
解决方案当你调用需要它们的C函数时,Swift将自己的类型映射到C指针。 Apple有一些关于此互动的文档:与C API交互。
总之,当你调用一个函数, c $ c> UnsafePointer< Type> ,它可以接受
nil
,inout
那种类型的数组(即[Type]
,你正在使用什么),或者其中一个通用的Swift指针类型。一个函数取UnsafePointer< Void>
可以取任何类型,对类型没有约束,所以你需要阅读函数的文档,看看它期望/将返回。Playing with raw data in Swift I came across something I don't understand.
NSData has a constructor:init(bytes: UnsafePointer<Void>, length: Int)
where the first bytes parameter is clearly of UnsafePointer type.
However, if I pass [Byte] object to this constructor, not only does the compiler not complain, but it works ok.
But if I try to cast [Byte] to UnsafePointer, I fail.
How does this work?For example (you can try it in Playgrounds):
let buffer: [Byte] = [0x00, 0xff] let data = NSData(bytes: buffer, length: buffer.count) // no error data.description var pointer: UnsafePointer<Void> // comment this line to avoid compiler error pointer = buffer // error
I know I can do
UnsafePointer<Void>(buffer)
but my question is, what does NSData constructor do implicitly, that I don't have to do that.
解决方案Swift maps its own types to C pointers when you're calling a C function that requires them. Apple has a bit of documentation on this interaction: Interacting with C APIs.
In short, when you're calling a function that takes an
UnsafePointer<Type>
, it can acceptnil
, aninout
variable of that type, an array of that type (i.e.,[Type]
, what you're using), or one of the generic Swift pointer types. A function takingUnsafePointer<Void>
can take any of those, with no constraint on the type at all, so you need to read the function's documentation to see what it expects/will return.这篇关于NSData(bytes:length :)如何将[Byte]转换为UnsafePointer< Void>在Swift?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!