gpt4 book ai didi

python - SWIG - 将 C 字符串数组包装到 python 列表

转载 作者:太空狗 更新时间:2023-10-30 00:19:53 25 4
gpt4 key购买 nike

我想知道使用 SWIG 将 C 中的字符串数组包装到 Python 列表的正确方法是什么。

数组在结构中:

typedef struct {
char** my_array;
char* some_string;
}Foo;

SWIG 自动将 some_string 包装成 python 字符串。

我应该在 SWIG 接口(interface)文件中放入什么,以便我可以在 Python 中访问 my_array 作为常规 Python 字符串列表 ['string1', 'string2' ]?

我已经按照建议使用了 typemap :

%typemap(python,out) char** {
int len,i;
len = 0;
while ($1[len]) len++;
$result = PyList_New(len);
for (i = 0; i < len; i++) {
PyList_SetItem($result,i,PyString_FromString($1[i]));
}
}

但是还是不行。在 Python 中,my_array 变量显示为 SwigPyObject:_20afba0100000000_p_p_char。

我想知道这是否是因为 char** 在结构中?也许我需要通知 SWIG?

有什么想法吗?

最佳答案

我认为在 SWIG 中没有自动处理此转换的选项。您需要使用 SWIG 的 Typemap 功能并手动编写类型转换器。在这里您可以找到从 Python 列表到 char** http://www.swig.org/Doc1.3/Python.html#Python_nn59 的转换。这样就完成了一半的工作。您现在需要做的是检查 Typemap 的其余文档并编写从 char** 到 Python 列表的转换器。

关于python - SWIG - 将 C 字符串数组包装到 python 列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5670456/

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