从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"
但是当我这样传递它时,dit无效
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.
谢谢.
推荐答案
不知道为什么,但是此代码有效.这会将字符串传递给C函数,该函数期望使用const char *,该字符似乎与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屋!