C数组char name [8]作为元组导入Swift:
(Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8)
名称的地址与名称[0]的地址相同,和
Swift保留从C导入的结构的内存布局
confirmed by Apple engineer Joe Groff:
… You can leave the struct defined in C and import it into Swift. Swift will respect C’s layout.
因此,我们可以传递record.name的地址,
转换成一个UInt8指针
String初始化器:
var record = someFunctionReturningAStructRecord()
// Swift 2:
let name = withUnsafePointer(&record.name) {
String.fromCString(UnsafePointer($0))!
}
// Swift 3:
let name = withUnsafePointer(to: &record.name) {
$0.withMemoryRebound(to: UInt8.self, capacity: MemoryLayout.size(ofValue: record.name)) {
String(cString: $0)
}
}
注意:假定名称[]中的字节是有效的NUL终止的UTF-8序列。