Search code examples
swiftfoundation

What is the best conversion from String into UnsafePointer<Int8>?


To convert String into UnsafePointer I use this:

var tail = ("" as NSString).utf8String

But is there any way to convert without NSString casting?

I use UnsafePointer inside C-library methods.


Solution

  • There's special method exactly for this: .withCString(_:):

    yourString.withCString { pointer in
        // work with the pointer
        return result
    }
    

    Or if you want it as property there's .utf8CString:

    var tail = "".utf8CString // ContiguousArray<CChar> (aka ContiguousArray<Int8>)
    // and then
    tail.withUnsafeBufferPointer { pointer in
        // work with the pointer
        return result
    }