ios – Swift中的unsigned char

前端之家收集整理的这篇文章主要介绍了ios – Swift中的unsigned char前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在Obj-C中,此代码用于将NSData转换为unsigned char:
unsigned char *dataToSentToPrinter = (unsigned char *)malloc(commandSize);

在Swift中,unsigned char被称为CUnsignedChar,但是如何在Swift中将NSData对象转换为CUnsignedChar?

解决方法

这可能是你正在寻找的:
let commandsToPrint: NSData = ...

// Create char array with the required size:
var dataToSentToPrinter = [CUnsignedChar](count: commandsToPrint.length,repeatedValue: 0)

// Fill with bytes from NSData object:
commandsToPrint.getBytes(&dataToSentToPrinter,length: sizeofValue(dataToSentToPrinter))

更新:实际上你根本不需要复制数据(两者都没有)
Objective-C代码也不在Swift中).有一个指向数据的指针就足够了.
所以你的代码看起来像这样(比较
Error (“‘()’ is not identical to ‘UInt8′”) writing NSData bytes to NSOutputStream using the write function in Swift
对于类似的问题):

let dataToSentToPrinter = UnsafePointer<CUnsignedChar>(commandsToPrint.bytes)
let commandSize = commandsToPrint.length
var totalAmountWritten = 0

while totalAmountWritten < commandSize {
    let remaining = commandSize - totalAmountWritten
    let amountWritten = starPort.writePort(dataToSentToPrinter,totalAmountWritten,remaining)
    totalAmountWritten += amountWritten
    // ...
}
原文链接:https://www.f2er.com/iOS/334812.html

猜你在找的iOS相关文章