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.

asked Aug 19, 2014 at 8:35
4
  • 2
    I think if you had const char* argument on C side it would work seamlessly. Commented Aug 19, 2014 at 8:40
  • Wojtek you are my hero! Thank you so much.. Solution: Changed c function to initSocket(const char* address) and string declaration to `var address: CString = "192.168.1.2" Thanks again! Commented Aug 19, 2014 at 8:47
  • @WojtekSurowka, Looks like an answer to me. Commented Aug 19, 2014 at 8:51
  • @WojtekSurowka: I think you should rewrite your comment as an answer so that it can be marked as the solution Commented Aug 19, 2014 at 8:51

2 Answers 2

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";
answered Aug 19, 2014 at 8:52
Sign up to request clarification or add additional context in comments.

1 Comment

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<UInt8> and Swift strings can automatically bridge to that. The type CString has been removed from the language.
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

answered Jan 23, 2020 at 7:08

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.