ios – Swift中的unsigned char

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

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

解决方法

这可能是你正在寻找的:
  1. let commandsToPrint: NSData = ...
  2.  
  3. // Create char array with the required size:
  4. var dataToSentToPrinter = [CUnsignedChar](count: commandsToPrint.length,repeatedValue: 0)
  5.  
  6. // Fill with bytes from NSData object:
  7. 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
对于类似的问题):

  1. let dataToSentToPrinter = UnsafePointer<CUnsignedChar>(commandsToPrint.bytes)
  2. let commandSize = commandsToPrint.length
  3. var totalAmountWritten = 0
  4.  
  5. while totalAmountWritten < commandSize {
  6. let remaining = commandSize - totalAmountWritten
  7. let amountWritten = starPort.writePort(dataToSentToPrinter,totalAmountWritten,remaining)
  8. totalAmountWritten += amountWritten
  9. // ...
  10. }

猜你在找的iOS相关文章