在 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))
Update:实际上你根本不需要复制数据(也不需要在
Objective-C 代码也不在 Swift 中)。拥有一个就足够了pointer到数据。
所以你的代码可能看起来像这样(比较使用 Swift 中的 write 函数将 NSData 字节写入 NSOutputStream 时出现错误(“'()' 与 'UInt8' 不同”) https://stackoverflow.com/questions/25080661/error-is-not-identical-to-uint8-writing-nsdata-bytes-to-nsoutputstrea对于类似的问题):
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
// ...
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)