6

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.

1
  • what if you typehint it to NSString instead? Commented Jun 5, 2014 at 1:50

2 Answers 2

10

This does the trick:

var s = NSString(bytes: infoLog, length: Int(infoLogLength), encoding: NSASCIIStringEncoding)
Sign up to request clarification or add additional context in comments.

Comments

2

Alternatively here is another option that compiles:

var infoLog = UnsafePointer<CChar>.alloc(Int(value))
glGetShaderInfoLog(shader, value, nil, infoLog)
var infoLogString = String.fromCString(infoLog)
infoLog.dealloc(Int(value))

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.