1

Update: This question is no longer relevant anymore because CString has been removed in Xcode 6 beta 4.


In C, I can pass a C string (const char *) to a C function that takes varargs.

Now I want to do the same thing in Swift given a CString. I know that in Swift I cannot access C varargs functions directly, but I can access C functions that take a va_list, which in Swift becomes CVaListPointer, and I can make that with getVaList() from an array of CVarArg, as per this question.

I can successfully put integers (Int) and objects (NSObject) into the CVarArg array with no problem, but I can't figure out how to get a CString into a CVarArg.

Looking through the types that conform to CVarArg in the standard library, I see that there is a COpaquePointer, but I can't figure out how to get CString into that either.

Community
  • 1
  • 1
user102008
  • 30,736
  • 10
  • 83
  • 104

2 Answers2

1

The following seems to compile for getting a CString into a COpaquePointer :

var myStr : CString = "foo"
var myStrPointer:CMutablePointer<CString> = &myStr
myStrPointer.withUnsafePointer { (myPtr1 : UnsafePointer<CString>) -> () in
  let myOpaquePtr = COpaquePointer(myPtr1)
}
hotpaw2
  • 70,107
  • 14
  • 90
  • 153
  • 1
    I am not sure this will work, `CString` probably already is pointer.. Maybe it would be better to get a `String` and then use `withCString { ...}` to get an `UnsafePointer` first. – Sulthan Jun 13 '14 at 20:28
  • are you sure this isn't the pointer to the variable `myStr` on the stack? – user102008 Jun 13 '14 at 20:48
1

This is tested working on beta 3:

let myString = "abc123"
let myStringC = myString.cStringUsingEncoding(NSUTF8StringEncoding)!

myStringC.withUnsafePointerToElements {
    (myStringPtr: UnsafePointer<CChar>) -> () in
    var varargs = [COpaquePointer(myStringPtr)]
    let va_list = getVaList(varargs)
    // Use va_list...
}
jbg
  • 4,903
  • 1
  • 27
  • 30
  • There is no `CString` in this code. `myString` is a `String`, and `myStringC` is a `[CChar]`. Although I can get a `String` from a `CString` with `String.fromCString()`, your process of going from `String` to `UnsafePointer` is much longer than using `withCString` directly as Sulthan's comment suggests. – user102008 Jul 17 '14 at 04:30
  • A C string and a C array of chars are the same thing. I tested the `withCString` method suggested by Sulthan and it didn’t work, but YMMV, I may have just messed something up when testing it. – jbg Jul 19 '14 at 01:51
  • `CString` and `[CChar]` are vastly different types in Swift. Why don't you try starting with a variable of type `CString`? – user102008 Jul 19 '14 at 05:03