How do I get a persistent pointer to a String?

I found String‘s generic instance method withCString(_:), but I need to get pointers to multiple strings and don’t want to have a bunch of nested closures. For example, let’s say that str1 and str2 are both String instances, foo and bar are both C struct types, and do_something is a C function. Then how do I do something like this?

let ptr1 = str1.pointerThatPersistsEvenAfterPassedToFunction let ptr2 = str2.pointerThatPersistsEvenAfterPassedToFunction let c_struct1 = foo(ptr1, 1, 2) let c_struct2 = bar(ptr2, 3, c_struct1) do_something(c_struct1, c_struct2) str1.invalidatePersistentPointer str2.invalidatePersistentPointer 
Add Comment
1 Answer(s)

You cannot safely access a Swift String‘s underlying buffer without using withCString.

So you can either use the nested closures which is the safest and most correct way to use the CStrings or you can use UnsafeMutablePointer<CChar> and allocate and manage the CStrings yourself.

Answered on August 31, 2020.
Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.