0

I have a C API, which has signature like:

SendPing(char * content);

Now, I want to call it from Swift. Swift seems like auto imported it as:

SendPing(content: UnsafeMutablePointer<Int8>!)

But, when I try it in Swift like:

var content:String = "sampledata"
SendPing(content)

I thought Swift can automatically handle "String" to "UnsafeMutablePointer" convertion but it doesn't. Reported error is: "Cannot convert value of type 'String' to expected argument type 'UnsafeMutablePointer!'. I remember it works in Swift 3.0 but I may be wrong.

What's the right way to handle this in Swift 4.2?


solution posted in question: Swift convert string to UnsafeMutablePointer<Int8> doesn't work for me. I couldn't figure out the root cause but I guess it's due to Swift 4.2.

5
  • I didn't notice before but this question has already been asked here. Commented Dec 24, 2018 at 5:43
  • Possible duplicate of Swift convert string to UnsafeMutablePointer<Int8> Commented Dec 24, 2018 at 5:44
  • @Kamran, thank you. I have tried the way in the link you provided but it doesn't work. My way seems like is simplest so far. Commented Dec 24, 2018 at 5:45
  • There are plenty of answers and seem to work. Not sure why they didn't work in your case. If you knew this is already asked then you could have added your answer under that question instead of duplicating the same question. Commented Dec 24, 2018 at 5:51
  • @Kamran, I spent hours in this and tried different answer from here but unfortunately I was not lucky enough. so, I post a new question. Very soon, I figured it out. This is what happened. I'm not intended to create a question and then answer by myself. Commented Dec 24, 2018 at 5:52

1 Answer 1

3

Follow up and Summary:

1) solution in link Swift convert string to UnsafeMutablePointer<Int8> is not valid in Swift 4 anymore.

2) To get an UnsafeMutablePointer(Int8) from a String, the simplest way is:

let contentPointer = strdup(content)

3) However, you should always keep in mind that it's caller's responsibility to free memory. Above code will use new memory and it must be deallocated afterwards.:

let contentPointer = strdup(content)
SendPing(content: contentPointer)
....

free(contentPointer)

Otherwise, you will face memory leak issue.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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.