2014-06-05 41 views
5

某些C API(例如, glGetShaderInfoLog,在緩衝區中返回字符數組。我需要將它們轉換爲字符串來使用它們。將Swift CChar數組轉換爲字符串

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' 

在這個例子中GLchar映射到雨燕CCHAR AKA INT8但對我的生活,我不能找到一個字符串或NSString的方法,將它初始化。

+0

如果你typehint該怎麼NSString的呢? – zneak

+0

相同的編譯錯誤。 – darrinm

回答

9

該做的伎倆:

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

另外這裏是編譯另一種選擇:

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