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.
Find React, Vue, or Angular mentors to help you master JS frameworks and libraries. To convert a string to an array, we can use the Array () intializer syntax in Swift. Here is an example, that splits the following string into an array of individual characters.
We have given a character array arr and the task is to convert char array to string str in C# . Using string() Method: The String class has several overloaded constructors which take an array of characters or bytes. Thus it can be used to create a new string from the character array.
1 Get the character array and its size. 2 Create an empty string. 3 Iterate through the character array. 4 As you iterate keep on concatenating the characters we encounter in the character array to the string. 5 Return the string.
Thus it can be used to create a new string from the character array. Using Join () Method: This method is used to concatenates the members of a collection or the elements of the specified array, using the specified separator between each member or element. Thus it can be used to create a new string from the character array.
This does the trick:
var s = NSString(bytes: infoLog, length: Int(infoLogLength), encoding: NSASCIIStringEncoding)
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With