Formatting CVaListPointer

So you’re using libtiff in Swift, and need to implement the TIFFErrorHandler.

Or, for whatever reason, you have a CVaListPointer (the args parameter, below) and a format string, and you want to format. Here’s how:

let errorHandler:TIFFErrorHandler = {
(moduleNamePtr, formatPtr, args) in
guard let formatPtr = formatPtr else {
// No format string - this is unexpected and there's
// not much we can do here, perhaps log that it happened.
return
}

// Convert the format pointer into a Swift String
let formatStr = String(cString:formatPtr)

// Create the output buffer
var buff = Data.init(count: 1024)

// Accessing the buffer's bytes...
buff.withUnsafeMutableBytes({ (ptr) -> () in
// Format into them
vsnprintf(ptr, 1024, formatStr.UTF8CString, args)
})

guard let formatted = String(data: buff, encoding: .utf8) else {
// This would only happen if the logging produced an invalid string,
// we don't have a string we can display
return
}

NSLog("TIFF error: \(formatted)")
}

TIFFSetErrorHandler(errorHandler)