-1

我已经构建了一个包含伪 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属性,一切正常,打印语句会打印一个“H”。但是,如果我尝试访问pointer.length,它会打印一个换行符,尽管我在 print 语句之后使用了该属性,并且长度为 0。这是一个错误还是我犯了一个错误?

4

1 回答 1

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
}
于 2018-08-16T22:11:13.140 回答