Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting from const char* to Swift string

Tags:

c

swift

I have a c function which I access from a bridging header that returns a const char*:

const char* get_c_string();

I then try to convert it to a Swift String:

let str = String.fromCString(UnsafePointer<Int8>(get_c_string()))
print(str)

... but it just prints garbage:

Optional("\u{14}\0\0")

I can find how to pass Swift string to C but not the other way around. How can I convert a const char* to a Swift String?

Thanks!

like image 647
Pat Mustard Avatar asked Oct 08 '15 14:10

Pat Mustard


1 Answers

Your Swift code is correct, you can shorten it slightly to

// Swift 2:
let str = String.fromCString(get_c_string())
// Swift 3:
let str = String(cString: get_c_string())

However, you must ensure that the pointer returned from the C function is still valid when the function returns. As an example

const char* get_c_string() {
    char s[] = "abc";
    return s;
}

returns the address of a local stack variable, which is undefined behavior.

You might have to duplicate the string (and then think of when and where to release the memory).

like image 54
Martin R Avatar answered Nov 02 '22 07:11

Martin R