How do I get a persistent pointer to a String?
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
str2 are both
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
You cannot safely access a Swift
String‘s underlying buffer without using
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