从 Swift 字符串转换为 const char* [英] Converting from Swift string to const char*
问题描述
我正在尝试将 const char * 传递给从 Swift 中的 Swift 字符串转换而来的旧 C 库.
I'm trying to pass a const char * to an old C library converted from a Swift string in Swift.
这是我正在调用的 C 函数:
This is the C function I'm calling:
artnet_node artnet_new(const char *ip, int verbose) { ...
如何将 Swift 字符串转换为这个 const char 类型?当我像这样传递 ipAddress 时它会起作用:
how can I convert a Swift string to this const char type? It works when I pass ipAddress like this:
internal var ipAddress = "192.168.1.43"
但是当我这样通过它时它不起作用
but dit does not work when I pass it like this
internal var ipAddress:String = "192.168.1.43"
我需要在需要指定类型的函数中使用它:
I need this in a function where I need to specify the type:
internal func setupArtnode(ip:String) -> Int{
我尝试使用 AnyObject 而不是 String 但这也不起作用.
I tried using AnyObject instead of String but that doesn't work either.
谢谢.
推荐答案
不知道为什么,但此代码有效.这将一个字符串传递给需要一个 const char* 的 C 函数,这似乎与 unsafePointer 相同.
Not sure why but this code is working. This passes a string to a C function expecting a const char* which seems to be the same as a unsafePointer.
internal func setupArtnode(ipAddress:String) -> NSInteger{
let cString = self.ipAddress.cString(using: String.defaultCStringEncoding)!
let newString:String = NSString(bytes: cString, length: Int(ipAddress.characters.count), encoding:String.Encoding.ascii.rawValue)! as String
let key2Pointer = UnsafePointer<Int8>(newString)
node = artnet_new(key2Pointer, Int32(verbose)) // VERBOSE : true(1) , false(0)
...
这篇关于从 Swift 字符串转换为 const char*的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!