Search code examples
swiftunsafe-pointers

Swift String to bytes in a buffer


I have a swift String that only contains ASCII characters. I have to put them in a char* buffer that I then cast to void* and to do this process in reverse to get the replied string.

Example:

bool query(const void* queryString, byte queryLength, void* replyBuffer, byte bufferLength);

So, I have to setup two buffers. One that will hold my query string and one, that is 180 bytes large, to contain the reply.

How can I setup those two buffers and copy back and forth the strings ? I tried exploring _bridgeToObjectiveC().utf8String ans well as unsafemutablepointer... but I feel lost...


Solution

  • This is how you can set up the buffers and pass them to the C function:

    let queryString = "Query ..."
    
    let queryBuffer = Array(queryString.utf8)
    var replyBuffer = Array(repeating: UInt8(0), count: 180)
    
    let result = query(queryBuffer, numericCast(queryBuffer.count), &replyBuffer, numericCast(replyBuffer.count))
    

    queryBuffer is an array with the UTF-8 representation of the string, and replyBuffer an array containing a specified amount of zero bytes.

    The arrays are passed to the function with queryBuffer and &replyBuffer, respectively, which passes pointers to the element storage to the C function.

    If the result buffer is filled with a null-terminated C string on return then you can create a Swift string with

    let resultString = String(cString: replyBuffer)