Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Swift CChar array into a String

Tags:

c

string

swift

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.

like image 397
darrinm Avatar asked Jun 05 '14 01:06

darrinm


People also ask

How to convert a string to an array in Swift?

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.

How to convert char array to string str in C #?

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.

How to convert a character array to a string in Python?

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.

How to create a new string from an array in PHP?

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.


2 Answers

This does the trick:

var s = NSString(bytes: infoLog, length: Int(infoLogLength), encoding: NSASCIIStringEncoding)
like image 163
darrinm Avatar answered Sep 18 '22 19:09

darrinm


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))
like image 30
FranticApparatus Avatar answered Sep 18 '22 19:09

FranticApparatus