gpt4 book ai didi

c - swift 3 : Compilation error converting String Array to C Char Array

转载 作者:太空宇宙 更新时间:2023-11-04 04:28:10 24 4
gpt4 key购买 nike

我有以下 C 结构:

typedef struct {
char** categories;
int category_size;
} category_fmc_s_type;

我的 Swift 数组具有以下值:

let categories = ["Weekday", "Weekend"]

我想用“工作日”和“周末”填充 C 结构字段“类别”。为此,我调用了 toPointer():

fileprivate static func toPointer(_ args: [String]) -> UnsafeMutablePointer<UnsafeMutablePointer<Int8>> {
let buffer = UnsafeMutablePointer<UnsafeMutablePointer<Int8>>.allocate(capacity: args.count)
for (index, value) in args.enumerated() {
buffer[index] = UnsafeMutablePointer<Int8>(mutating: (value as NSString).utf8String!)
}
return buffer
}

我不断收到以下 XCode 8 错误:

Cannot convert value of type 'UnsafeMutablePointer<UnsafeMutablePointer<Int8>>' to expected argument type 'UnsafeMutablePointer<UnsafeMutablePointer<Int8>?>!'

有什么建议吗?我不明白为什么有可选的和'!'在 C-Struct 定义中隐含。

最佳答案

由于编译器作为错误发出,您需要在 Int8 w/"?"之后解包,如下所示。

fileprivate func toPointer(_ args: [String]) -> UnsafeMutablePointer<UnsafeMutablePointer<Int8>?> {
let buffer = UnsafeMutablePointer<UnsafeMutablePointer<Int8>?>.allocate(capacity: args.count)
for (index, value) in args.enumerated() {
buffer[index] = UnsafeMutablePointer<Int8>(mutating: (value as NSString).utf8String!)
}
return buffer
}

然后,

func testMyCat() {
let categories = ["Weekday", "Weekend"]
let buffer = toPointer(categories)
var mycat = category_fmc_s_type()
mycat.categories = buffer // you would see compile error w/o "?"
}

上面的代码没有错误。 Martin's solution

处给出编译错误

mycat.categories = &cargs(查看链接)

我不知道为什么。

关于c - swift 3 : Compilation error converting String Array to C Char Array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39269909/

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