zneak zneak - 1 month ago 19
Swift Question

Converting a C char array to a String

I have a Swift program that does interop with a C library. This C library returns a structure with a

char[]
array inside, like this:

struct record
{
char name[8];
};


The definition is correctly imported into Swift. However, the field is interpreted as a tuple of 8
Int8
elements (typed
(Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8)
), which I have no idea how to transform into a
String
with Swift.

There is no
String
initializer that accepts an
Int8
tuple, and it doesn't seem possible to get a pointer to the first element of the tuple (since types can be heterogenous, that's not really surprising).

Right now, my best idea is to create a tiny C function that accepts a pointer to the structure itself and return
name
as a
char*
pointer instead of an array, and go with that.

Is there, however, are pure Swift way to do it?

Answer

You can get a pointer to the tuple with

withUnsafePointer(&record.name) { ... }

(this requires record to be a variable). The pointer can then be converted to anUnsafePointer<Int8> and used in String.fromCString():

var record = someFunctionReturningAStructRecord()

let name = withUnsafePointer(&record.name) {
    String.fromCString(UnsafePointer($0))!
}

This assumes that the bytes in name[] are a valid NUL-terminated UTF-8 sequence.

Comments