我正在尝试将const char *传递给从Swift中的Swift字符串转换而来的旧C库.
artnet_node artnet_new(const char *ip,int verbose) { ...
如何将Swift字符串转换为此const char类型?当我像这样传递ipAddress时,它可以工作:
internal var ipAddress = "192.168.1.43"
但是当我像这样传递时,dit不起作用
internal var ipAddress:String = "192.168.1.43"
我需要在一个需要指定类型的函数中使用它:
internal func setupArtnode(ip:String) -> Int{
我尝试使用AnyObject而不是String,但这也不起作用.
谢谢.
您应该能够将String直接传递给期望const char *的C函数,并且它将自动转换为以null结尾的UTF-8字符串:
原文链接:https://www.f2er.com/swift/319951.htmllet string = "string" let node = artnet_new(string,1)
有关更多信息,请参见Interacting with C APIs .以下是相关摘录:
When a function is declared as taking an UnsafePointer argument,
it can accept any of the following:
- A String value,if Type is Int8 or UInt8. The string will automatically be converted to UTF8 in a buffer,and a pointer to that buffer is passed to the function.