失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > c 语言数组转换字符串 数组 – 将C字符数组转换为字符串

c 语言数组转换字符串 数组 – 将C字符数组转换为字符串

时间:2018-09-02 05:18:00

相关推荐

c 语言数组转换字符串 数组 – 将C字符数组转换为字符串

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序列。

如果觉得《c 语言数组转换字符串 数组 – 将C字符数组转换为字符串》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。