xudesheng
xudesheng

Reputation: 1102

Swift 4 convert String to UnsafeMutablePointer<Int8>

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.

Upvotes: 0

Views: 1205

Answers (1)

xudesheng
xudesheng

Reputation: 1102

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.

Upvotes: 3

Related Questions