6

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.

Mads Gadeberg
  • 1,429
  • 3
  • 20
  • 30

2 Answers2

6

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";
Wojtek Surowka
  • 20,535
  • 4
  • 44
  • 51
  • 8
    You may want to update that question. With Swift 2.2 or newer, Swift strings are not automatically bridged to C strings. C strings are now `UnsafePointer` and Swift strings can automatically bridge to that. The type `CString` has been removed from the language. – Mecki Sep 06 '16 at 21:15
2

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

kc ochibili
  • 3,103
  • 2
  • 25
  • 25