Converting Swift string to CChar pointer

In my fast paced application project, I need to interact with the C API. One of the C functions takes a char pointer as input, so I need to convert my swift string to a char pointer. But I don't know how to do it properly.

Here's my sample code:

var user_id_ptr : UnsafeMutablePointer<CChar> = UnsafeMutablePointer.alloc(100)
var cusID = "123"  
user_id_ptr.memory = cusID.cStringUsingEncoding(NSUTF8StringEncoding)!

      

And I always got this error:  Cannot assign a value of type '[CChar]' to a value of type 'CChar'

I also check the answer for: UnsafeMutablePointer <Int8> from string in Swift

The above answer is slightly different from mine. The example above is for just one character, but I have a string. Also, I have to pass multiple arguments to the function, I cannot use something like let result = "N" .withCString {dgeev_ (UnsafeMutablePointer ($ 0), UnsafeMutablePointer ($ 0), & N, ...)}. Please show me an example on how to do this.

+3


source to share


1 answer


If the C function does not mutate the strings passed as arguments, then the parameters must be declared as const char *

, for example

int func1(const char *s1, const char *s2);

      

and in this case you can just pass Swift strings that are automatically converted (compare the String value with the parameter of the UnsafePointer <UInt8> function) :

let str1 = "first string argument"
let str2 = "second string argument"

let result1 = func1(str1, str2)

      

If the function parameters are declared as char *



int func2(char *s1, char *s2);

      

then you should use withCString()

to get a temporary representation of the string as an array of UTF-8 characters with NUL ends:

let str1 = "first string argument"
let str2 = "second string argument"

// Swift 2:
let result2 = str1.withCString { s1 in
    str2.withCString { s2 in
        func2(UnsafeMutablePointer(s1), UnsafeMutablePointer(s2))
    }
}

// Swift 3:
let result2 = str1.withCString { s1 in
    str2.withCString { s2 in
        func2(UnsafeMutablePointer(mutating: s1), UnsafeMutablePointer(mutating: s2))
    }
}

      

Note that this still assumes that the function does not mutate the passed strings, the conversion is UnsafeMutablePointer()

necessary to make the compiler happy.

+8


source







All Articles