从为const char *转换为字符串斯威夫特 [英] Converting from const char* to Swift string
问题描述
我有一个C函数,我从一个桥接报头,返回一个为const char *访问
:
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")
我可以找到如何斯威夫特字符串传递给C,但不是周围的其他方式。我怎么能转换为const char *
来一个斯威夫特字符串?
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?
谢谢!
推荐答案
您斯威夫特code是正确的,可以将其缩短稍微
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())
但是,你必须确保指针从C函数返回
是当函数返回仍然有效。作为一个例子
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).
这篇关于从为const char *转换为字符串斯威夫特的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!