Skip to content

Commit da42b43

Browse files
authored
Merge pull request #65057 from plotfi/init-String-with-NSString-utf8String
[cxx-interop] Adding std.string initializer for UnsafePointer<CChar>?
2 parents 7032225 + 6180387 commit da42b43

File tree

3 files changed

+34
-0
lines changed

3 files changed

+34
-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

test/Interop/Cxx/stdlib/overlay/std-string-overlay.swift

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -236,4 +236,11 @@ StdStringOverlayTestSuite.test("std::u16string as Swift.CustomStringConvertible"
236236
expectEqual(cxx3.description, "a�c")
237237
}
238238

239+
StdStringOverlayTestSuite.test("std::string from C string") {
240+
let str = "abc".withCString { ptr in
241+
std.string(ptr)
242+
}
243+
expectEqual(str, std.string("abc"))
244+
}
245+
239246
runAllTests()

0 commit comments

Comments
 (0)