Skip to content

Commit c237f9f

Browse files
committed
[cxx-interop] Adding std.string initializer for UnsafePointer<CChar>?
Currently without an initializer for the unsafe char pointer type swiftc hits an assert around not being able to handle conversions of unsafe pointers with Any type. This patch adds the ability to convert to a std::string. This is to address issue #61218
1 parent c28031c commit c237f9f

File tree

2 files changed

+27
-0
lines changed

2 files changed

+27
-0
lines changed

stdlib/public/Cxx/std/String.swift

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,20 @@ extension std.string {
2525
self.push_back(value_type(bitPattern: char))
2626
}
2727
}
28+
29+
public init(_ string: UnsafePointer<CChar>?) {
30+
self.init()
31+
32+
guard let str = string else {
33+
return
34+
}
35+
36+
let len = strlen(str)
37+
for i in 0..<len {
38+
let char = UInt8(str[i])
39+
self.push_back(value_type(bitPattern: char))
40+
}
41+
}
2842
}
2943

3044
extension std.u16string {
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
// RUN: %target-swift-frontend -I %S/Inputs -cxx-interoperability-mode=swift-5.9 -emit-ir %s -Xcc -fignore-exceptions | %FileCheck %s
2+
3+
// REQUIRES: objc_interop
4+
5+
import Foundation
6+
import CxxStdlib
7+
8+
// CHECK: @"\01L_selector(UTF8String)"
9+
// CHECK: @objc_msgSend
10+
// CHECK: call swiftcc void @"$sSo3stdO3__1O0067basic_stringInt8char_traitsInt8allocatorInt8_FABErpaBGcqaGHerapGgqaV9CxxStdlibEyAFSPys4Int8VGSgcfC"
11+
12+
let ObjCStr: NSString = "hello"
13+
let CxxStr = std.string(ObjCStr.utf8String) // Should not crash here

0 commit comments

Comments
 (0)