How to cast `UnsafePointer<T>?` to `UnsafePointer<T?>`?

With a string literal, you’re right that it will work, even though it’s still invalid Swift - the string’s data is likely stored in the constant data section of the binary and therefore should always have a valid pointer. For non-constant strings, the last use of the string’s data is in the vk.ApplicationInfo, so the compiler is free to release any memory associated with that string immediately after that call, potentially invalidating any pointers derived from it. The difference between Swift and C here is that in C values live until the end of the current scope, whereas in Swift they live until their last usage.

Again, this all may work today, but be prepared for it to break in strange edge cases or with new compiler optimisations.

1 Like

Thomas is right, but I think the language could do with being stronger: do not rely on this behaviour. It is wrong, it is memory unsafe, and one day you will regret it.

If you want the C representation of the string to live for longer than the single call site, you must ask for it to live that long by using withCString. If that duration exceeds the lifetime of a function call, you must allocate a pointer and copy the bytes into it to force them into a single location in memory.

Ok, I'll follow your advises guys and do the right way..

However, to come back to the original problem of my thread, I resolved by using withMemoryRebound (more here)

1 Like
Terms of Service

Privacy Policy

Cookie Policy