how to convert swift::string to char * in cpp

I have a need to interoperate between cpp and swift. Here when we return a 'String' type from swift to cpp, the type that we receive in cpp is 'swift::string'.

I wanted to convert 'swift::string' to char* in cpp. Any help on how can this be achieved in cpp?

I have tried the below solution, but it seems to be unsafe as it is giving warning:

// swift method that return UnsafeMutablePointer which gets casted to char * in cpp

  let x =  mySwiftString.cString(using: .utf8)
  return UnsafeMutablePointer<CChar>(mutating: x)   

  // warning at return : Initialization of 'UnsafeMutablePointer<CChar>' (aka 'UnsafeMutablePointer<Int8>') results in a dangling pointer


Return a swift::String. Convert that to a std::string in your C++ code, and then use its .c_str() method to get the char*. Be aware that the lifetime of the char* is the same as the std::string.

Why do you want a char*, rather than a std::string?

std::string is the equivalent of swift string, and you can copy characters from the std::string. Refer https://developer.apple.com/documentation/swift/callingapisacrosslanguageboundaries sample xcode project that has many examples of strings being passed back and forth.

how to convert swift::string to char * in cpp
 
 
Q