10

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?

Sam Pettersson
  • 3,049
  • 6
  • 23
  • 37
  • Your Objective-C code *allocates* an unsigned char buffer, I cannot see how it *converts* NSData. Perhaps you can explain better what you actually need to achieve. – Martin R Oct 10 '14 at 12:52
  • It takes the data from the commandSize which is NSData, convert might be the wrong word, but I simply need that data to become an unsigned char buffer. – Sam Pettersson Oct 10 '14 at 12:56
  • I'm trying to convert an Obj-C function from the StarIO SDK which looks like this http://pastebin.com/dBCz2bv0, if that gives you an idea of what I'm trying to do. – Sam Pettersson Oct 10 '14 at 13:01

1 Answers1

14

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
    // ...
}
Community
  • 1
  • 1
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382