gpt4 book ai didi

c - Swift 字符串数组转换为 const char * const *

转载 作者:太空宇宙 更新时间:2023-11-04 07:02:07 26 4
gpt4 key购买 nike

我在将 Swift 字符串数组转换为具有签名的 c 函数数组时遇到问题:

PGconn *PQconnectStartParams(const char * const *keywords, const char * const *values, int expand_dbname)

在 Swift 中,const char * const * 显示为:

<UnsafePointer<UnsafePointer<Int8>>

所以我尝试转换名为“选项”的字典 [String:String] 的内容,并将其提供给函数,如下所示:

var keys = [[Int8]]()
var values = [[Int8]]()
for (key, value) in options {
var int8Array = key.cStringUsingEncoding(NSUTF8StringEncoding)!
keys.append(int8Array)
int8Array = value.cStringUsingEncoding(NSUTF8StringEncoding)!
values.append(int8Array)
}
pgConnection = PQconnectStartParams(UnsafePointer(keys), UnsafePointer(values), 0)

可以编译运行,但是函数不起作用。

如有任何见解,我们将不胜感激。

最佳答案

这并不完美,但至少有效。

let options = ["key1": "value1", "key2": "value2", "key3": "value3", "key4": "value4"]

var keys = [String]()

for (key, value) in options {

keys.append(key)
}

//you need to identify how many paramenters should be provided and set them following "static way"
//I did not find how to prepare this dynamically
let cKey1 = keys[0].cStringUsingEncoding(String.defaultCStringEncoding())!
let key1Pointer = UnsafePointer<CChar>(cKey1)

let cKey2 = keys[1].cStringUsingEncoding(String.defaultCStringEncoding())!
let key2Pointer = UnsafePointer<CChar>(cKey2)

let cKey3 = keys[2].cStringUsingEncoding(String.defaultCStringEncoding())!
let key3Pointer = UnsafePointer<CChar>(cKey3)

let cKey4 = keys[3].cStringUsingEncoding(String.defaultCStringEncoding())!
let key4Pointer = UnsafePointer<CChar>(cKey4)


let keysCArray = [key1Pointer, key2Pointer, key3Pointer, key4Pointer]

f(keysCArray)

/*
C - code

void f(const char * const *keywords) {

printf("%s\n", keywords[0]);
printf("%s\n", keywords[1]);
printf("%s\n", keywords[2]);
printf("%s\n", keywords[3]);

}
*/

希望对您有所帮助。如果您愿意,我可以分享我的示例应用。

关于c - Swift 字符串数组转换为 const char * const *,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36783767/

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