zneak zneak - 1 year ago 134
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

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
elements (typed
(Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8)
), which I have no idea how to transform into a
with Swift.

There is no
initializer that accepts an
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
as a
pointer instead of an array, and go with that.

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

Answer Source

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

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download