ambientlight ambientlight - 5 months ago 183
Swift Question

Swift3: Proper way to convert string to null-terminated C-string

I am interfacing with libxml2 in swift, and the C APIs binding (still) produce

UnsafePointer<Int8>!
for c-strings. Whereas Swift APIs normally result in
UnsafePointer<UInt8>!
.

So my question is - am I doing the string to null-terminated C-string conversion correctly?

let cfilePath = unsafeBitCast(myStringString.nulTerminatedUTF8.withUnsafeBufferPointer { $0.baseAddress }, to: UnsafePointer<Int8>.self)


Should I instead prefer using some other method instead of just bypassing Swift type checking with interpreting
UInt8
bytes as
Int8
bytes?

Answer

don't use unsafeBitCast for that!!

let cstr = "alpha".nulTerminatedUTF8
let int8arr = cstr.map{ Int8(bitPattern: $0) }
let uint8arr = Array(cstr)
print(int8arr.dynamicType, uint8arr.dynamicType)
// Array<Int8> Array<UInt8>

update

let uint8: UInt8 = 200
let int8 = Int8(bitPattern: uint8)
print(uint8, int8)
// 200 -56
Comments