简体   繁体   English

如何获得指向字符串的持久指针?

[英]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.我发现String的通用实例方法withCString(_:) ,但我需要获取指向多个字符串的指针,并且不想有一堆嵌套的闭包。 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.例如,假设str1str2都是String实例, foobar都是 C 结构类型,而do_something是 C 函数。 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 withCString .不使用withCString就不能安全地访问 Swift String的底层缓冲区。

So you can either use the nested closures which is the safest and most correct way to use the CString s or you can use UnsafeMutablePointer<CChar> and allocate and manage the CString s yourself.因此,您可以使用嵌套闭包,这是使用CString的最安全和最正确的方法,或者您可以使用UnsafeMutablePointer<CChar>并自己分配和管理CString

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM