user5892643 user5892643 - 1 year ago 121
Swift Question

Array of Swift Strings into const char * const *

I am having trouble converting an array of Swift Strings into an array for a c function with the signature:

PGconn *PQconnectStartParams(const char * const *keywords, const char * const *values, int expand_dbname)

In Swift, the const char * const * shows up as:


So I try to convert the contents of a Dictionary [String:String] called 'options' and feed that to the function as follows:

var keys = [[Int8]]()
var values = [[Int8]]()
for (key, value) in options {
var int8Array = key.cStringUsingEncoding(NSUTF8StringEncoding)!
int8Array = value.cStringUsingEncoding(NSUTF8StringEncoding)!
pgConnection = PQconnectStartParams(UnsafePointer(keys), UnsafePointer(values), 0)

It compiles and runs, but the function does not work.

Any insight would be greatly appreciated.

Answer Source

That's not perfect but at least it works.

let options = ["key1": "value1", "key2": "value2", "key3": "value3", "key4": "value4"]

var keys = [String]()

for (key, value) in options {


//you need to identify how many paramenters should be provided and set them following "static way"
//I did not find how to prepare this dynamically
let cKey1 = keys[0].cStringUsingEncoding(String.defaultCStringEncoding())!
let key1Pointer = UnsafePointer<CChar>(cKey1)

let cKey2 = keys[1].cStringUsingEncoding(String.defaultCStringEncoding())!
let key2Pointer = UnsafePointer<CChar>(cKey2)

let cKey3 = keys[2].cStringUsingEncoding(String.defaultCStringEncoding())!
let key3Pointer = UnsafePointer<CChar>(cKey3)

let cKey4 = keys[3].cStringUsingEncoding(String.defaultCStringEncoding())!
let key4Pointer = UnsafePointer<CChar>(cKey4)

let keysCArray = [key1Pointer, key2Pointer, key3Pointer, key4Pointer]


 C - code

 void f(const char * const *keywords) {

 printf("%s\n", keywords[0]);
 printf("%s\n", keywords[1]);
 printf("%s\n", keywords[2]);
 printf("%s\n", keywords[3]);


Hope it helps. I can share my sample app if you want.

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