8
在對象 - 這個代碼是用來一個NSData轉換爲unsigned char無符號的字符:斯威夫特
unsigned char *dataToSentToPrinter = (unsigned char *)malloc(commandSize);
在斯威夫特無符號的字符是所謂叫做CUnsignedChar,但我怎麼轉換一個NSData對象CUnsignedChar在迅速?
在對象 - 這個代碼是用來一個NSData轉換爲unsigned char無符號的字符:斯威夫特
unsigned char *dataToSentToPrinter = (unsigned char *)malloc(commandSize);
在斯威夫特無符號的字符是所謂叫做CUnsignedChar,但我怎麼轉換一個NSData對象CUnsignedChar在迅速?
這可能是你在找什麼:
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))
更新:其實你並不需要將數據在所有複製(無論在 Objective-C代碼也不斯威夫特)。對於數據有一個指針就足夠了。 所以,你的代碼看起來是這樣的(比較 Error ("'()' is not identical to 'UInt8'") writing NSData bytes to NSOutputStream using the write function in Swift 了類似的問題):
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
// ...
}
你的Objective-C代碼* *分配無符號的字符緩衝區,我看不出它如何* *轉換NSData的。也許你可以更好地解釋你實際需要達到的目標。 – 2014-10-10 12:52:53
它從commandData的數據是NSData,轉換可能是錯誤的詞,但我只需要該數據成爲一個無符號字符緩衝區。 – 2014-10-10 12:56:05
我試圖從StarIO SDK轉換一個Obj-C函數,看起來像這個http://pastebin.com/dBCz2bv0,如果這給你一個我想要做的事情的想法。 – 2014-10-10 13:01:29