I'm trying to interact with an old C terminal app from Swift. I've successfully integrated the source code and bridged the headers from C to Swift. The code compiles and runs from Xcode 6.3 beta. I've renamed the terminal app's main entry point to:
int initialize(int argc, char **argv);
Nevertheless, I'm struggling to pass the arguments from Swift to this C function. My challenge is to convert the arguments in the right format. Typical input from Swift would look like:
let args = ["-c", "1.2.3.4", "-p", "8000"]
I've tried messing with "cStringUsingEncoding(NSUTF8StringEncoding)" and "withUnsafePointer", but no luck so far. Any help is greatly appreciated!
Building on Martin’s answer, if you find yourself doing this a lot, you could wrap the dup/free part into a function in a similar style to
String.withCString
:The C function
is mapped to Swift as
This is a possible solution:
It uses the fact that in
strdup($0)
the Swift string$0
is automatically converted to a C string, as explained in String value to UnsafePointer<UInt8> function parameter behavior.