与传统的迅速C端的应用程序进行交互 [英] Interact with legacy C terminal app from swift
问题描述
我想与斯威夫特的旧的C端的应用进行互动。我已经成功地集成了源$ C $ c和桥接头从C到斯威夫特。在code编译并从X $ C $运行Ç6.3测试版。我已经改名为终端应用程序的主入口点:
I'm trying to interact with an old C terminal app from Swift. I've successfully integrated the source code and bridged the headers from C to Swift. The code compiles and runs from Xcode 6.3 beta. I've renamed the terminal app's main entry point to:
int initialize(int argc, char **argv);
不过,我挣扎着从斯威夫特的参数传递给这个C函数。我的挑战是如何转换参数以正确的格式。从雨燕典型的输入将如下所示:
Nevertheless, I'm struggling to pass the arguments from Swift to this C function. My challenge is to convert the arguments in the right format. Typical input from Swift would look like:
let args = ["-c", "1.2.3.4", "-p", "8000"]
我试过用cStringUsingEncoding(NSUTF8StringEncoding)和withUnsafePointer搞乱,但至今没有运气。任何帮助是极大AP preciated!
I've tried messing with "cStringUsingEncoding(NSUTF8StringEncoding)" and "withUnsafePointer", but no luck so far. Any help is greatly appreciated!
推荐答案
C函数
int initialize(int argc, char **argv);
映射到斯威夫特
func initialize(argc: Int32, argv: UnsafeMutablePointer<UnsafeMutablePointer<Int8>>) -> Int32
这是一个可能的解决方案:
This is a possible solution:
let args = ["-c", "1.2.3.4", "-p", "8000"]
// Create [UnsafeMutablePointer<Int8>]:
var cargs = args.map { strdup($0) }
// Call C function:
let result = initialize(Int32(args.count), &cargs)
// Free the duplicated strings:
for ptr in cargs { free(ptr) }
它使用的事实,即在的strdup($ 0)
雨燕字符串 $ 1,0
自动转换为C字符串,
在<一个解释href=\"http://stackoverflow.com/questions/27063569/string-value-to-unsafepointeruint8-function-parameter-behavior\">String价值UnsafePointer&LT;&UINT8 GT;功能参数的行为。
It uses the fact that in strdup($0)
the Swift string $0
is automatically converted to a C string,
as explained in String value to UnsafePointer<UInt8> function parameter behavior.
这篇关于与传统的迅速C端的应用程序进行交互的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!