Convert Swift CChar array into a String

c, string, swift

Solution

This does the trick:

var s = NSString(bytes: infoLog, length: Int(infoLogLength), encoding: NSASCIIStringEncoding)

Problem

Some C APIs, e.g. glGetShaderInfoLog, return character arrays in buffers. I need to convert them to Strings to use them. ``` var value: GLint = 0 glGetShaderiv(shader, GLenum(GL_INFO_LOG_LENGTH), &value) var infoLog: GLchar[] = GLchar[](count: Int(value), repeatedValue: 0) var infoLogLength: GLsizei = 0 glGetShaderInfoLog(shader, value, &infoLogLength, &infoLog) var s: String = NSString.stringWithUTF8String(infoLog) // Compile Error: Cannot convert the expression's type 'NSString!' to type 'CString' ``` In this example GLchar maps to the Swift type CChar AKA Int8 but for the life of me I can't find a String or NSString method that will initialize with it.

Original source