【问题标题】:Convert an String to an array of int8将 String 转换为 int8 数组
【发布时间】:2015-02-12 05:48:38
【问题描述】:

我有一个包含 C 字符串的 C 结构(旧库,等等等等),现在我需要将 CFString 和 Swift 字符串转换成这个 c 字符串。类似的东西

struct Product{
   char name[50];
   char code[20];
}

所以我试图将其分配为

productName.getCString(&myVarOfStructProduct.name, maxLength: 50, encoding: NSUTF8StringEncoding)

但编译器给了我以下错误:无法将类型 (int8, int8, int8....) 转换为 [CChar]。

【问题讨论】:

标签: string swift


【解决方案1】:

一个可能的解决方案:

withUnsafeMutablePointer(&myVarOfStructProduct.name) {
    strlcpy(UnsafeMutablePointer($0), productName, UInt(sizeofValue(myVarOfStructProduct.name)))
}

在块内部,$0 是指向元组的(可变)指针。这个指针是 如预期的那样转换为UnsafeMutablePointer<Int8> BSD library function strlcpy().

它还使用了 Swift 字符串 productName 自动 到UnsafePointer&lt;UInt8&gt;String value to UnsafePointer<UInt8> function parameter behavior 中所述。正如 cmets 中提到的那样 线程,这是通过创建一个临时的UInt8 数组(或序列?)来完成的。 所以或者你可以显式枚举 UTF-8 字节并将它们放入 进入目的地:

withUnsafeMutablePointer(&myVarOfStructProduct.name) {
    tuplePtr -> Void in
    var uint8Ptr = UnsafeMutablePointer<UInt8>(tuplePtr)
    let size = sizeofValue(myVarOfStructProduct.name)
    var idx = 0
    if size == 0 { return } // C array has zero length.
    for u in productName.utf8 {
        if idx == size - 1 { break }
        uint8Ptr[idx++] = u
    }
    uint8Ptr[idx] = 0 // NUL-terminate the C string in the array.
}

另一种可能的解决方案(使用中间 NSData 对象):

withUnsafeMutablePointer(&myVarOfStructProduct.name) {
    tuplePtr -> Void in
    let tmp = productName + String(UnicodeScalar(0)) // Add NUL-termination
    let data = tmp.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)!
    data.getBytes(tuplePtr, length: sizeofValue(myVarOfStructProduct.name))
}

Swift 3 更新:

withUnsafeMutablePointer(to: &myVarOfStructProduct.name) {
    $0.withMemoryRebound(to: Int8.self, capacity: MemoryLayout.size(ofValue: myVarOfStructProduct.name)) {
        _ = strlcpy($0, productName, MemoryLayout.size(ofValue: myVarOfStructProduct.name))
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-04-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-21
    • 2021-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多