Working with C strings in Swift, or: How to convert UnsafePointer to CString

后端 未结 2 787
夕颜
夕颜 2020-12-15 16:24

While playing with Standard C Library functions in Swift, I came across problems when passing C strings around. As a simple example (just to demonstrate the problem), the St

相关标签:
2条回答
  • 2020-12-15 17:22

    The String struct in Swift has an init routine you can use like:

    let myString = String(cString: myUnsafePointer)
    

    see also init(cString: UnsafePointer)

    0 讨论(0)
  • 2020-12-15 17:29

    Swift 1.1 (or perhaps earlier) has even better C string bridging:

    let haystack = "This is a simple string"
    let needle = "simple"
    let result = String.fromCString(strstr(haystack, needle))
    

    The CString type is gone completely.

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