在Obj-C中,此代码用于将NSData转换为无符号字符:

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
    // ...
}

10-08 05:57