ambientlight ambientlight - 2 years ago 370
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

for c-strings. Whereas Swift APIs normally result in

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
bytes as

Answer Source

don't use unsafeBitCast for that!!

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


let uint8: UInt8 = 200
let int8 = Int8(bitPattern: uint8)
print(uint8, int8)
// 200 -56
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download