gpt4 book ai didi

c - 这个 C 函数 int search(const char * const input_words[]) 的 swift 签名是什么以及如何从 Swift 调用它?

转载 作者:行者123 更新时间:2023-11-30 10:16:36 25 4
gpt4 key购买 nike

如何从 Swift 调用以下 C 函数以及它的 swift 签名是什么?

int search(const char * const input_words[])

此函数期望 C 字符串采用 EUC 日语编码,我已经采用了所需的形式。但是如何在 swift 中创建 C 字符串的 this C 数组?

我尝试调整 How to pass an array of Swift strings to a C function taking a char ** parameter 中建议的解决方案:

    let args = ["-c", "1.2.3.4", "-p", "8000"]

// Create [UnsafeMutablePointer<Int8>]:
var cargs = args.map { strdup($0) }

search(&cargs) // This gives me "Cannot invoke 'search'
// with an argument list of type '(inout
// Array<UnsafeMutablePointer<Int8>>)'".

XCode 是否会生成一些我可以查找的内容?我查看了 Derived 文件夹,但没有找到任何东西。我不知道该函数的 swift 签名是什么以及如何调用它。

最佳答案

我认为解决了它(在你的帮助下)。函数签名为:

    func search(input_words: UnsafePointer<UnsafePointer<Int8>>) -> Int32

现在我的示例代码如下:

    var args = ["-c", "1.2.3.4", "-p", "8000"]

// Create [UnsafePointer<Int8>]:
let cargs: [UnsafePointer<Int8>] = args.map{UnsafePointer<Int8>(strdup($0))}

search(cargs)

这似乎按预期运行。我使用以下虚拟函数对其进行了测试:

    int search(const char * const input_words[]){
int i;
for (i = 0; i < 10 && input_words[i] != NULL; i++) {
NSLog(@"word: %s", input_words[i]);
}
NSLog(@"i: %i", i);
return 1;
}

这给了我以下有意义的输出:

2015-04-15 17:02:22.886 示例[3492:49189] 字:-c
2015-04-15 17:02:22.889 示例[3492:49189] 字:1.2.3.4
2015-04-15 17:02:22.889 示例[3492:49189] 字:-p
2015-04-15 17:02:22.889 示例[3492:49189]字数:8000
2015-04-15 17:02:35.904 示例[3492:49189] i: 4

如果有更好的方法,请告诉我。再次感谢您给我的支持和建议。美好的结局。

关于c - 这个 C 函数 int search(const char * const input_words[]) 的 swift 签名是什么以及如何从 Swift 调用它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29628870/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com