Reputation: 303
Hello i'm trying to use an old legacy C library that uses buffers (unsigned char []) to transform the data. The main issue here is that I couldn't find a way to transform a String to a CUnsignedChar and then be able to alloc that buffer to a UnsafeMutablePointer
Upvotes: 0
Views: 2803
Reputation: 41
I turn String to NSData first ,then turn NSData to CUnsignedChar array
if let data = str.dataUsingEncoding(NSUTF8StringEncoding){
var rawData = [CUnsignedChar](count: data.length,repeatedValue: 0)
data.getBytes(&rawData, length: data.length)
}
Upvotes: 0
Reputation: 385660
If you want to convert a Swift string to an immutable C string to pass to a C function, try this:
let s: String = "hello, world!"
s.nulTerminatedUTF8.withUnsafeBufferPointer { p -> Void in
puts(UnsafePointer<Int8>(p.baseAddress))
Void()
}
You may need to use UnsafePointer<UInt8>
if your function takes an unsigned char *
.
Upvotes: 2