[swift-users] Ugliness bridging Swift String to char *
Guillaume Lessard
glessard at tffenterprises.com
Mon Mar 6 13:23:02 CST 2017
> On Mar 6, 2017, at 12:28 AM, Kenny Leung via swift-users <swift-users at swift.org> wrote:
>
> Follow-up on this:
>
> The StaticString solution doesn’t work:
>
> let separator: StaticString = “|”
> opt.fieldSep = UnsafeMutablePointer(mutating: separator.utf8start)
>
> … because utf8start returns UnsafePointer<UInt8>, and fieldSep is actually UnsafeMutablePointer<Int8>. There doesn’t seem to be any way to convert UnsafePointer<Unit8> to UnsafePointer<Int8>.
There is: .withMemoryRebound()
var opt = PQPrintOpt()
let sep2: StaticString = "|"
opt.fieldSep = sep2.utf8Start.withMemoryRebound(to: Int8.self, capacity: sep2.utf8CodeUnitCount) {
buffer in
let p = UnsafeMutablePointer<Int8>.allocate(capacity: sep2.utf8CodeUnitCount)
p.assign(from: buffer, count: sep2.utf8CodeUnitCount)
return p
}
// use opt
opt.fieldSep.deinitialize(count: sep2.utf8CodeUnitCount)
opt.fieldSep.deallocate(capacity: sep2.utf8CodeUnitCount)
Cheers,
Guillaume Lessard
More information about the swift-users
mailing list