在Obj-C中,此代码用于将NSData转换为unsigned char:
unsigned char *dataToSentToPrinter = (unsigned char *)malloc(commandSize);
在Swift中,unsigned char被称为CUnsignedChar,但是如何在Swift中将NSData对象转换为CUnsignedChar?
答案 0 :(得分:13)
这可能就是你要找的东西:
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
// ...
}