Search code examples
iosswiftunsafe-pointers

Convert CUnsignedChar pointer to CChar pointer


I have an objective C function that gives me a

UnsafePointer<UInt8>/UnsafePointer<CUnsignedChar>. 

However I need this data as a

UnsafePointer<Int8>

unfortunately the function I require doesn't take

UnsafePointer<UInt8>.

Solution

  • In your case an "unsafe bit cast" would be the easiest solution:

    let ptr: UnsafePointer<UInt8> = ...
    let i8ptr = unsafeBitCast(ptr, to: UnsafePointer<Int8>.self)
    

    Another option is "memory rebinding":

    ptr.withMemoryRebound(to: Int8.self, capacity: <count>) { i8ptr in
        // ...
    }