gpt4 book ai didi

swift - UnsafeMutablePointer 的奇怪行为

转载 作者:行者123 更新时间:2023-11-30 11:14:22 27 4
gpt4 key购买 nike

我构建了一个小结构,其中包含伪 C 字符串 UnsafeMutablePointer。现在我想添加一种方法来获取字符串的长度,但有些行为非常奇怪:

struct Char {
let value: CChar

init(_ char: CChar) {
self.value = char
}
}

extension Char: CustomStringConvertible {
var description: String {
return String(UnicodeScalar(UInt8(bitPattern: self.value)))
}
}

extension Char: Equatable {
public static func ==(lhs: Char, rhs: Char) -> Bool {
return lhs.value == rhs.value
}
}

struct CharPointer {
let pointer: UnsafeMutablePointer<Char>

init(_ string: String) {
let chars = string.cString(using: .utf8)!.map { Char($0) }
self.pointer = UnsafeMutablePointer(mutating: chars)
}

subscript(_ offset: Int) -> Char {
get { return self.pointer[offset] }
set { self.pointer[offset] = newValue }
}

var length: Int {
var ptr = self.pointer

while ptr.pointee != Char(0) {
ptr += 1
}

return ptr - self.pointer
}
}

let pointer = CharPointer("Hello World!")

print(pointer[0])

// print(pointer.length)

如果我不使用 length 属性,一切都会正常工作,并且 print 语句会打印“H”。但是,如果我尝试访问 pointer.length,它会打印一个换行符,尽管我在 print 语句之后使用了该属性,并且长度为 0。这是一个错误还是我犯了一个错误?

最佳答案

感谢@Hamish,我找到了一个解决方案,我只需使用数组中的指针初始化第二个指针:

init(_ string: String) {
let chars = string.cString(using: .utf8)!.map { Char($0) }
let pointer = UnsafeMutablePointer(mutating: chars)
let pointer2 = UnsafeMutablePointer<Char>.allocate(capacity: chars.count)
pointer2.initialize(from: pointer, count: chars.count)

self.pointer = pointer2
}

关于swift - UnsafeMutablePointer 的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51885587/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com