Search code examples
cswiftstringxcode14

How to convert from C char buffer to String in Swift in XCode 14?


There's a ton of references to this question but none of them seem to work. I'm using Xcode 14.1. What am I doing wrong?

I have a C buffer in a struct:

struct MY_C_STRUCT
{
    char buff[256];   //Contains null-terminated C-string in UTF-8 encoding
};

and I have a Swift struct where I'm trying to set its variable from MY_C_STRUCT::buff:

class MyStruct : ObservableObject
{
    @Published public var Buff : String = ""

    func from_MY_C_STRUCT(mi : MY_C_STRUCT)
    {
         Buff = String(cString: mi.buff)
    }
}

That gives me on the String(cString:) line:

No exact matches in call to initializer


Solution

  • As this blog explains, Swift imports fixed-sized C arrays as tuples!

    One way to treat the tuple as a buffer is to use withUnsafeBytes to get a pointer to the memory and then pass that pointer to String(cString:):

    Replace:

    Buff = String(cString: mi.buff)
    

    with:

    Buff = withUnsafeBytes(of: mi.buff) { (rawPtr) -> String in
        let ptr = rawPtr.baseAddress!.assumingMemoryBound(to: CChar.self)
        return String(cString: ptr)
    }