Skip to content

[cxx-interop] Adding std.string initializer for UnsafePointer<CChar>? #65057

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 13, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions stdlib/public/Cxx/std/String.swift
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,20 @@ extension std.string {
self.push_back(value_type(bitPattern: char))
}
}

public init(_ string: UnsafePointer<CChar>?) {
self.init()

guard let str = string else {
return
}

let len = strlen(str)
for i in 0..<len {
let char = UInt8(str[i])
self.push_back(value_type(bitPattern: char))
}
}
}

extension std.u16string {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
// RUN: %target-swift-frontend -I %S/Inputs -cxx-interoperability-mode=swift-5.9 -emit-ir %s -Xcc -fignore-exceptions | %FileCheck %s

// REQUIRES: objc_interop

import Foundation
import CxxStdlib

// CHECK: @"\01L_selector(UTF8String)"
// CHECK: @objc_msgSend
// CHECK: call swiftcc void @"$sSo3stdO3__1O0067basic_stringInt8char_traitsInt8allocatorInt8_FABErpaBGcqaGHerapGgqaV9CxxStdlibEyAFSPys4Int8VGSgcfC"

let ObjCStr: NSString = "hello"
let CxxStr = std.string(ObjCStr.utf8String) // Should not crash here
7 changes: 7 additions & 0 deletions test/Interop/Cxx/stdlib/overlay/std-string-overlay.swift
Original file line number Diff line number Diff line change
Expand Up @@ -236,4 +236,11 @@ StdStringOverlayTestSuite.test("std::u16string as Swift.CustomStringConvertible"
expectEqual(cxx3.description, "a�c")
}

StdStringOverlayTestSuite.test("std::string from C string") {
let str = "abc".withCString { ptr in
std.string(ptr)
}
expectEqual(str, std.string("abc"))
}

runAllTests()