Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unsigned char in Swift

Tags:

ios

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?

like image 602
Sam Pettersson Avatar asked Oct 10 '14 12:10

Sam Pettersson


1 Answers

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
    // ...
}
like image 190
Martin R Avatar answered Oct 27 '22 14:10

Martin R