Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a Swift string to a c function?

I am having serious trouble passing a string from swift, to a function written in c.

I'm trying to do this in my swift code

var address = "192.168.1.2"
var port = 8888

initSocket(address, port)

The c function looks like this:

void initSocket(char *address, int port);

Im getting the error: Cannot convert the expression's of type 'Void' to type 'CMutablePointer'

I can't seem to find a solution that works.

like image 331
Mads Gadeberg Avatar asked Aug 19 '14 08:08

Mads Gadeberg


2 Answers

Swift CStrings work seamlessly with C constant strings, so use

void initSocket(const char *address, int port);

instead of char* argument, and declare your address variable as CString:

var address: CString = "192.168.1.2";
like image 113
Wojtek Surowka Avatar answered Nov 11 '22 17:11

Wojtek Surowka


in C, declare your parameter like this

void setLastName(const char* lastName){

}

then in swift, you can directly pass in a regular swift string

setLastName("Montego");

the key is to define the variable with the asterisk immediately after the char in C like: const char*

source: https://developer.apple.com/swift/blog/?id=6

like image 30
kc ochibili Avatar answered Nov 11 '22 17:11

kc ochibili