Importing C++ strings, experimental feature

Hi there,
Just a quick question about a comment in the C++ Interoperability Status document: swift/CppInteroperabilityStatus.md at main · apple/swift · GitHub
It notes that std::string can be used from Swift.

When trying an experiment using the toolchain snapshot from March 30th, a C++ string imports as the following type name:
__CxxTemplateInstNSt3__112basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEEE

Is this expected and what is meant by 'can be used from Swift'? Just so I am not misunderstanding. :slight_smile:

I can index into this type and get raw values - and I can query it's length.

Sincerely,
/morten

Hi! What's the context for where you see the mangled name for the std::string? Is that the only typename available to you, or can you actually use std.string in Swift? In the past the mangled name has come up in certain diagnostic when the user used the actual std.string type.

1 Like

Hi Alex,
Thanks for your reply!
I only see it when I explicitly print the type(of:) the value - or when doing a debug print of the value.

So my confusion was about the fact that the "string can be used from Swift" is not the same as attempting to bridge to a Swift String.

It does look like it's straight forward to do a manual bridging - although I don't know enough about C++ to tell if the c_str() would always give a pointer to a buffer of utf8 characters or whether that might differ.

I see, thanks. That's something we will most likely fix so that you get a demangled type name.

So my confusion was about the fact that the " string can be used from Swift" is not the same as attempting to bridge to a Swift String .

We don't intend to automatically bridge std::string to Swift's String type. You will need to keep using std::string from Swift, but we will provide convenience C++ standard library overlays that will make it easier to obtain a Swift String from std::string. We will update the status documentation to make this fact clearer.

2 Likes

Thanks for the explanation - and for all the hard work in creating the C++ interoperability!

2 Likes