Passing Swift String type to a Cpp function in the new interop

I have implemented the new cpp-swift interop mechanism using modulemap file. I have a use case to pass a swift string to the cpp function. I observed that the below code works and I am able to pass a swift String type directly to a cpp function which received it as const char *. This works only if its received as const char * in cpp(and not char *). However, this is not an interop documented behaviour for interoperating String types and wanted to know whether this is safe to use. If not, can someone suggest an alternative approach to pass a swift string to Cpp.

// Swift code
 public static func StringToCharPointer () -> Void
    {
       // calling cpp function and passing a swift String type as argument, which is received as const char *

        Student.Convert (sUItextdata)    //sUItextdata is of type 'String'   
    }

//static Cpp function
void Student::Convert (const char * pStr)
{
    std::string s(pStr);
    std::cout << "char * converted from swift String : " << s << std::endl;
}

Note : I am aware that there is a way to pass it to cpp and receive it as std:string, but I do not wish to use that.

However, this is not an interop documented behaviour for interoperating String types

That’s because it’s not a feature of C++ interoperability, but inherited from C interoperability. It’s this same feature that makes strdup work in this program:

import Darwin

func main() {
    let d = strdup("Hello Cruel World!")!
    print(strlen(d))
}

main()

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

Passing Swift String type to a Cpp function in the new interop
 
 
Q