Use a C function in Swift
I want to use a C function in Swift that has the following method definition:
int startTest(char *test1, char* test2)
If I call this method from my Swift code like this
startTest("test1", "test2")
The following error message appears:
'String' is not convertible to 'UnsafeMutablePointer<Int8>'
If I change my method definition to:
int startTest(const char *test1, const char* test2)
and call this method like this:
var test1 = "test1"
var test2 = "test2"
startTest(&test1, &test2)
I get
'String' is not identical to 'Int8'
So my question is, how can I use the C function? (this is part of the library, so changing the method call can be problematic).
Thanks in advance!
+3
source to share
1 answer
When
int startTest(const char *test1, const char* test2);
you can call a function from Swift just like
let result = startTest(test1, test2)
(without operator addresses). Swift strings are converted automatically to C Strings for function calls
When
int startTest(char *test1, char* test2);
you need to call the function with a buffer (variable) Int8
because the Swift compiler has to assume that strings can be modified from within a C function.
Example:
var cString1 = test1.cStringUsingEncoding(NSUTF8StringEncoding)!
var cString2 = test2.cStringUsingEncoding(NSUTF8StringEncoding)!
let result = startTest(&cString1, &cString2)
+5
source to share