简体   繁体   English

Swift 4将String转换为UnsafeMutablePointer <Int8>

[英]Swift 4 convert String to UnsafeMutablePointer<Int8>

I have a C API, which has signature like: 我有一个C API,其签名如下:

SendPing(char * content);

Now, I want to call it from Swift. 现在,我想从Swift调用它。 Swift seems like auto imported it as: Swift似乎自动将其导入为:

SendPing(content: UnsafeMutablePointer<Int8>!)

But, when I try it in Swift like: 但是,当我在Swift中尝试时,例如:

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

I thought Swift can automatically handle "String" to "UnsafeMutablePointer" convertion but it doesn't. 我以为Swift可以自动将“ String”转换为“ UnsafeMutablePointer”,但事实并非如此。 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. 报告的错误是:“无法将'String'类型的值转换为预期的参数类型'UnsafeMutablePointer!'。我记得它在Swift 3.0中有效,但我可能是错的。

What's the right way to handle this in Swift 4.2? 在Swift 4.2中处理此问题的正确方法是什么?


solution posted in question: Swift convert string to UnsafeMutablePointer<Int8> doesn't work for me. 问题发布的解决方案: 快速将字符串转换为UnsafeMutablePointer <Int8>对我不起作用。 I couldn't figure out the root cause but I guess it's due to Swift 4.2. 我不知道根本原因,但我想这是由于Swift 4.2而引起的。

Follow up and Summary: 跟进和总结:

1) solution in link Swift convert string to UnsafeMutablePointer<Int8> is not valid in Swift 4 anymore. 1)链接Swift中将字符串转换为UnsafeMutablePointer <Int8>的解决方案在Swift 4中不再有效。

2) To get an UnsafeMutablePointer(Int8) from a String, the simplest way is: 2)要从字符串获取UnsafeMutablePointer(Int8),最简单的方法是:

let contentPointer = strdup(content)

3) However, you should always keep in mind that it's caller's responsibility to free memory. 3)但是,您应始终牢记释放内存是调用者的责任。 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. 否则,您将面临内存泄漏问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM