3

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!

3
  • Well you have a function accepting two chars but you're calling it with two strings. Commented Sep 2, 2014 at 20:26
  • Yes, but how can I cast a String to a char*? Thats exactly my problem, because the C function does not know String type, it can only work with char* Commented Sep 2, 2014 at 20:30
  • This question and answer might be more googlable if there was something in the title about char * and/or const char *. Perhaps consider editing? Commented Sep 2, 2014 at 20:34

1 Answer 1

5

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) 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.