I'm working with a third party c API I'm trying to call one of the functions with a simple string. Something like this:
some_c_func("aString");
I get a build error:
Type 'UnsafeMutablePointer<char_t>' does not conform to protocol 'StringLiteralConvertible'
I've seen some suggestions to use utf8 on String or similar conversions, which gets nearly there, but with the following error:
some_c_func("aString".cStringUsingEncoding(NSUTF8StringEncoding));
'UnsafePointer<Int8>' is not convertible to 'UnsafeMutablePointer<char_t>'
How can I create an UnsafeMutablePointer?
It all depends on what
char_tis.If
char_tconverts toInt8then the following will work.This can be collapsed to
WARNING! This second method will cause a crash if
func cStringUsingEncoding(_:)returnsnil.Updating for Swift 3, and to fix memory leak
If the C string is only needed in a local scope, then no
strdup()is needed.cStringwill have the same memory lifecycle asstr(well similar at least).If the C string needs to live outside the local scope, then you will need a copy. That copy will need to be freed.