简体   繁体   中英

unsigned char in Swift

In Obj-C this code is used to convert an NSData to 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?

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). 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):

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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