Chris R.
Chris R.

Reputation: 425

Use C function in Swift

I want to use a C function in Swift, which 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")

I get the following error message:

'String' is not convertible to 'UnsafeMutablePointer<Int8>'

If I change my method definition to:

int startTest(const char *test1, const char* test2)

and call that 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? (it is part of a library, so changing the method call could be problematic).

Thanks in advance!

Upvotes: 3

Views: 1305

Answers (1)

Martin R
Martin R

Reputation: 540005

In the case of

int startTest(const char *test1, const char* test2);

you can call the function from Swift simply as

let result = startTest(test1, test2)

(without the address-of operators). The Swift strings are converted automatically to C Strings for the function call

In the case of

int startTest(char *test1, char* test2);

you need to call the function with a (variable) Int8 buffer, because the Swift compiler must assume that the strings might be modified from the C function.

Example:

var cString1 = test1.cStringUsingEncoding(NSUTF8StringEncoding)!
var cString2 = test2.cStringUsingEncoding(NSUTF8StringEncoding)!
let result = startTest(&cString1, &cString2)

Upvotes: 5

Related Questions