我对字符串有问题。与cstring{}结合使用的是UnsafeMutablePointer(mutating:…)。
给定:这样的C函数

randomSign(xml_string: UnsafeMutablePointer<Int8>!) -> Uint

同时给出:一个字符串
str = "some xml_tag"

我的工作代码是这样的(版本1)
func randomSignWrapper_1(xml_tag_str: String) -> Uint {
    let result = xml_str.withCString { s in return
       randomSign(UnsafeMutablePointer(mutating: s))
    }
    return result
}

但我想把withCString放到一个单独的函数中,比如:
func testFunction(_ x: String) -> UnsafeMutablePointer<Int8>{
    return x.withCString{s in
        return UnsafeMutablePointer(mutating: s)
    }
}

以便我可以轻松地重用它(版本2)
func randomSignWrapper_2(xml_tag_str: String) -> Uint {
    let result = randomSign(testFunction(xml_tag_str))
    return result
}

但问题是版本1提供了正确的返回值,而版本2却不知何故不能正常工作,并告诉我数据是错误的。
我想知道它为什么会这样?
如何解决它,我可以使用它描述的方式?

最佳答案

检查reference of withCString(_:)
讨论
withCString(:)方法确保序列的生存期
通过执行body扩展指向body的指针参数是
仅在闭包的生存期内有效。不要逃避
关闭以便以后使用。
您的版本代码试图将其从闭包中转义,以便以后使用。它不是withCString(_:)的有效用法。
包含String的UTF-8表示的区域是暂时的,Swift运行时将随时发布它。
你可以这样写:

func utf8Array(from string: String) -> [Int8] {
    return string.cString(using: .utf8)!
}

func randomSignWrapper_3(xml_tag_str: String) -> UInt {
    var charArray = utf8Array(from: xml_tag_str)
    let result = randomSign(xml_string: &charArray)
    return result
}

但我想知道你是否需要定义一个像utf8Array(from:)这样的函数。

关于c - 将string.withCString和UnsafeMutablePointer(mutating:cstring)包装到函数中,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/44026115/

10-11 01:30