A Swift String can be passed as an argument to a function taking
a UnsafePointer<Int8> parameter. The compiler generates a temporary representation of the Swift string
as a NUL-terminated sequence of char and passes a pointer to
that C String to the function. The representation and the pointer is only valid during the function call. That is what happens at
strlen(swiftString)
When assigning a global C string pointer then you have to take the
lifetime of this pointer into account. One possibility is
let swiftString = "Hello world"
swiftString.withCString {
CGlobalStruct.stringPtr = $0
// Pointer valid inside this closure ...
}
// Pointer not valid anymore ...
where a pointer to a C string representation is passed to the closure.
This pointer is (only) valid during the execution of the closure.
For longer-lived usage you could allocate a C string in memory,
but then you are responsible for freeing that memory eventually:
guard let cStringPtr = strdup(swiftString) else {
fatalError("strdup failed")
}
CGlobalStruct.stringPtr = UnsafePointer(cStringPtr)
// ...
free(cStringPtr)