UnsafeMutablePointer的奇怪行为

时间:2018-08-16 21:29:39

标签: swift unsafe-pointers unsafemutablepointer

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

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,但它会打印换行符。这是错误还是我做错了?

1 个答案:

答案 0 :(得分: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
}