简体   繁体   English

NSData(bytes:length :)如何将[Byte]转换为UnsafePointer <Void> 在斯威夫特?

[英]How does NSData(bytes:length:) convert [Byte] to UnsafePointer<Void> in Swift?

Playing with raw data in Swift I came across something I don't understand. 在Swift中使用原始数据我遇到了一些我不理解的东西。
NSData has a constructor: NSData有一个构造函数:

init(bytes: UnsafePointer<Void>, length: Int)

where the first bytes parameter is clearly of UnsafePointer type. 其中第一个bytes参数显然是UnsafePointer类型。
However, if I pass [Byte] object to this constructor, not only does the compiler not complain, but it works ok. 但是,如果我将[Byte]对象传递给此构造函数,不仅编译器不会抱怨,而且它可以正常工作。
But if I try to cast [Byte] to UnsafePointer , I fail. 但是如果我尝试将[Byte]转换UnsafePointer ,我就会失败。
How does this work? 这是如何运作的?

For example (you can try it in Playgrounds): 例如(您可以在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. 但我的问题是,NSData构造函数隐式地做了什么,我不必这样做。

Swift maps its own types to C pointers when you're calling a C function that requires them. 当您调用需要它们的C函数时,Swift将自己的类型映射到C指针。 Apple has a bit of documentation on this interaction: Interacting with C APIs . Apple提供了一些关于此交互的文档: 与C API交互

In short, when you're calling a function that takes an UnsafePointer<Type> , it can accept nil , an inout variable of that type, an array of that type (ie, [Type] , what you're using), or one of the generic Swift pointer types. 简而言之,当你调用一个接受UnsafePointer<Type>的函数时,它可以接受nil ,该类型的inout变量,该类型的数组(即[Type] ,你正在使用的),或者一个通用的Swift指针类型。 A function taking UnsafePointer<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. 采用UnsafePointer<Void>函数可以采用任何一种函数,对类型没有任何约束,因此您需要阅读函数的文档以查看它期望/将返回的内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM