简体   繁体   English

Swift中的unsigned char

[英]unsigned char in Swift

In Obj-C this code is used to convert an NSData to unsigned char: 在Obj-C中,此代码用于将NSData转换为unsigned char:

unsigned char *dataToSentToPrinter = (unsigned char *)malloc(commandSize);

In Swift unsigned char is supposedly called CUnsignedChar, but how do i convert an NSData object to CUnsignedChar in Swift? 在Swift中,unsigned char被称为CUnsignedChar,但是我如何在Swift中将NSData对象转换为CUnsignedChar?

This could be what you are looking for: 这可能是你正在寻找的:

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: Actually you don't need to copy the data at all (neither in the Objective-C code nor in Swift). 更新:实际上你根本不需要复制数据(既不在Objective-C代码也不在Swift中)。 It is sufficient to have a pointer to the data. 有一个指向数据的指针就足够了。 So your code could look like this (compare Error ("'()' is not identical to 'UInt8'") writing NSData bytes to NSOutputStream using the write function in Swift for a similar problem): 所以你的代码看起来像这样(比较Error(“'()'与'UInt8'不相同”)使用Swift中的write函数将NSData字节写入NSOutputStream以解决类似的问题):

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM