本文介绍了将String转换为UnsafePointer< xmlChar>的快捷方法在Swift 3(libxml2)中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为 libxml2 C库开发一个Swift 3包装器.

I'm working on a Swift 3 wrapper for the libxml2 C-library.

有两种方便的方法可以将String转换为UnsafePointer<xmlChar>,反之亦然.在libxml2中,xmlChar被声明为unsigned char.

There are two convenience methods to convert String to UnsafePointer<xmlChar> and vice versa. In libxml2 xmlChar is declared as unsigned char.

  • UnsafePointer<xmlChar>String并不复杂

func stringFrom(xmlchar: UnsafePointer<xmlChar>) -> String {
    let string = xmlchar.withMemoryRebound(to: CChar.self, capacity: 1) {
        return String(validatingUTF8: $0)
    }
    return string ?? ""
}

  • 对于StringUnsafePointer<xmlChar>,我尝试了很多事情,例如

  • For String to UnsafePointer<xmlChar> I tried many things for example

    let bytes = string.utf8CString.map{ xmlChar($0) }
    return UnsafePointer<xmlChar>(bytes)
    

    但是这不起作用,我发现的唯一可行的解​​决方案是

    but this doesn't work, the only working solution I figured out is

    func xmlCharFrom(string: String) -> UnsafePointer<xmlChar> {
        let pointer = (string as NSString).utf8String
        return unsafeBitCast(pointer, to: UnsafePointer<xmlChar>.self)
    }
    

  • 有没有一种更好的 swiftier 方式,而无需将桥接转换为NSStringunsafeBitCast?

    Is there a better, swiftier way without the bridge cast to NSString and unsafeBitCast?

    推荐答案

    我能想到的最快的方法是只使用bitPattern:初始化程序:

    Swiftiest way I can think of is to just use the bitPattern: initializer:

    let xmlstr = str.utf8CString.map { xmlChar(bitPattern: $0) }

    这将为您提供xmlCharArray.挂在上面,当需要将UnsafePointer传递给某些东西时,请使用ArraywithUnsafeBufferPointer方法:

    This will give you an Array of xmlChars. Hang onto that, and use Array's withUnsafeBufferPointer method when you need to pass an UnsafePointer to something:

    xmlstr.withUnsafeBufferPointer { someAPIThatWantsAPointer($0.baseAddress!) }

    不要让UnsafePointer从闭包中逸出,因为它在外面不会有效.

    Don't let the UnsafePointer escape from the closure, as it won't be valid outside it.

    这是如何妥协的?不用让函数返回指针,而是让它闭包.

    How's this for a compromise? Instead of having your function return a pointer, have it take a closure.

    func withXmlString<T>(from string: String, handler: (UnsafePointer<xmlChar>) throws -> T) rethrows -> T {
        let xmlstr = string.utf8CString.map { xmlChar(bitPattern: $0) }
    
        return try xmlstr.withUnsafeBufferPointer { try handler($0.baseAddress!) }
    }
    

    或者,作为String上的扩展名:

    Or, as an extension on String:

    extension String {
        func withXmlString<T>(handler: (UnsafePointer<xmlChar>) throws -> T) rethrows -> T {
            let xmlstr = self.utf8CString.map { xmlChar(bitPattern: $0) }
    
            return try xmlstr.withUnsafeBufferPointer { try handler($0.baseAddress!) }
        }
    }
    

    这篇关于将String转换为UnsafePointer&lt; xmlChar&gt;的快捷方法在Swift 3(libxml2)中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

    09-19 00:09