Convert Swift string to C char array

Hi


I have a C-API which I've imported using a bridging header. My C-API looks something like this:


// C-header
typedef struct Person {
     char name[50];
     char description[80];
} Person;

void addPerson(const Person* p);


Now I've figured out how to convert Person.name char-array to a Swift string using String.fromCString(). But how to I convert a Swift string to a C char-array.

I've tried:


// Swift app
var p : Person()
var s = "some name"
s.getCString(&p.name.0, 50, NSUTF8StringEncoding)
addPerson(&p)


But getCString() only accepts [CChar] and not an UnsafePointer<CChar>.


So my question is: how to I convert a Swift string to a C style char array (like Person.name)?


Regards

-- Bjoern

Accepted Answer

You should be able to just pass the Swift string. The const char * parameter of the C method should be converted to UnsafePointer<Int8> on the Swift side which can be passed as a Swift String (automatically translated).


Note the following quote from the Swift Cocoa iBook:

"A String value, if Type is Int8 or UInt8. The string will automatically be converted to UTF8 in a buffer that lasts for the duration of the call."

Excerpt From: Apple Inc. “Using Swift with Cocoa and Objective-C (Swift 2 Prerelease).” iBooks.

Ah, that was too easy 🙂 I see Swift even has strncpy() 🙂


Thanks!

I'm also having trouble using a string as a parameter. My function in C return a char * Array and as parameter It have folder(char *str) in the Swift side It tells me that It Is an unsafemutablepointer. I can't find a way to use a string var from Swift as an argument in the function in the Swift code. Sorry for the bad english >.<

You should better start a new thread for your own. Not many readers get attention to a thread marked as SOLVED.

Anyway, you need to provide more context specific for your issue. Including more code would be better.

Convert Swift string to C char array
 
 
Q