Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
949 views
in Technique[技术] by (71.8m points)

swift - Convert an String to an array of int8

I have an C struct (old library, blah blah blah) which contains an C string, now I need to convert CFString and Swift strings into this c string. Something like

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

So I'm trying to assign it as

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

but the compiler is giving me the following error: cannot convert type (int8, int8, int8....) to [CChar].

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

A possible solution:

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

Inside the block, $0 is a (mutable) pointer to the tuple. This pointer is converted to an UnsafeMutablePointer<Int8> as expected by the BSD library function strlcpy().

It also uses the fact that the Swift string productName is automatically to UnsafePointer<UInt8> as explained in String value to UnsafePointer<UInt8> function parameter behavior. As mentioned in the comments in that thread, this is done by creating a temporary UInt8 array (or sequence?). So alternatively you could enumerate the UTF-8 bytes explicitly and put them into the destination:

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.
}

Yet another possible solution (with an intermediate NSData object):

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))
}

Update for 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))
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...