Converting from const char* to Swift string

前端 未结 1 1379
心在旅途
心在旅途 2020-12-06 08:26

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 t

相关标签:
1条回答
  • 2020-12-06 08:48

    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).

    0 讨论(0)
提交回复
热议问题