Converting 'String' Type in Swift to 'const char *' in C++

126 Views Asked by At

I have the below code where my Swift code calls a C++ function. In this the Swift calls a C++ function and passes a Swift String as an argument to it, which is then received in the C++ code as const char *. This conversion works without any errors. Is this a documented behaviour in C++-Swift interoperability and is this safe to use?

Swift side:

internal static func CharCheck (pSentence: String) -> Void {
    TWSoundLogic.CharacterSoundCount (pSentence)
}

In the C++ side,

void TWSoundLogic::CharacterSoundCount (const char * pSentence) {
    ..
}

However, on returning a String type from a Swift function and trying to receive it as a const char* in C++, it gives an error in C++. Below is the code.

No viable conversion from 'swift::String' to 'const char *'

Swift side:

internal static func CharCheck () -> String {
    ..
    return sentence
}

In the C++ side,

void TWSoundLogic::CharacterSoundCount (const char * pSentence) {
    const char * cppsentence = swiftClass::CharCheck(); //error
}

Why does it not allow to return, but it allows to pass as argument? Can someone explain this behaviour?

1

There are 1 best solutions below

0
Duncan C On

Swift uses a variety of different internal storage methods to store String objects. I would suggest the following:

Convert your String to Data using a specific encoding like UTF8.

Pass the resulting Data (Which is a memory buffer) to C++ as a Char *. You'll need to work out ownership of the resulting memory. I haven't dealt with interoperability between Swift and C++ so I'm not sure how to go about that. Off the top of my head I'd say give Swift a way to ask C++ to allocate (malloc) a buffer sized for the contents of the Data, then cast that data to an unsafe mutable buffer and copy the data into it. It would then be your C++ code's responsibility to release the malloc'ed buffer once it is done with it.

Your C++ code will need to be written to assume the encoding (e.g. UTF8)