简体   繁体   English

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

[英]SWIG - Wrap C string array to python list

I was wondering what is the correct way to wrap an array of strings in C to a Python list using SWIG. 我想知道使用SWIG将C中的字符串数组包装到Python列表的正确方法是什么。

The array is inside a struct : 数组在struct中:

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

SWIG automatically wraps some_string to a python string. SWIG自动将some_string包装到python字符串中。

What should I put in the SWIG interface file so that I can access my_array in Python as a regular Python string list ['string1', 'string2' ] ? 我应该把什么放在SWIG接口文件中,以便我可以在Python中访问my_array作为常规Python字符串列表['string1','string2']?

I have used typemap as sugested : 我使用了typemap作为sugested:

%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]));
  }
}

But that still didn't work. 但那仍然行不通。 In Python, the my_array variable appears as SwigPyObject: _20afba0100000000_p_p_char. 在Python中,my_array变量显示为SwigPyObject:_20afba0100000000_p_p_char。

I wonder if that is because the char** is inside a struct? 我想知道是不是因为char **在一个结构中? Maybe I need to inform SWIG that? 也许我需要通知SWIG?

Any ideas? 有任何想法吗?

I don't think there is a option to handle this conversion automatically in SWIG. 我不认为在SWIG中可以自动处理此转换。 You need use Typemap feature of SWIG and write type converter manually. 您需要使用SWIG的Typemap功能并手动编写类型转换器。 Here you can find a conversion from Python list to char** http://www.swig.org/Doc1.3/Python.html#Python_nn59 so half of job is done. 在这里,您可以找到从Python列表到char ** http://www.swig.org/Doc1.3/Python.html#Python_nn59的转换,因此完成了一半的工作。 What you need to do right now is to check rest of documentation of Typemap and write converter from char** to Python list. 您现在需要做的是检查Typemap的其余文档并将转换器从char **写入Python列表。

I am not an expert on this but I think: 我不是这方面的专家,但我认为:

%typemap(python,out) char** {

applies to a function that returns char **. 适用于返回char **的函数。 Your char ** is inside a structure.. have a look at the code generated by swig to confirm the map got applied or not. 你的char **在一个结构中..看看swig生成的代码,以确认地图是否被应用。

You might have to use something like: 您可能必须使用以下内容:

%typemap(python,out) struct Foo {

To have a map that works on a structure Foo that gets returned. 要有一个适用于返回的结构Foo的映射。

Background: I used the same typemap definition as you used, but then for a char ** successfully. 背景:我使用了与您使用的相同的类型映射定义,但后来成功地使用了char **。

I am sorry for being slightly off-topic, but if it is an option for you I would strongly recommend using ctypes instead of swig. 我很抱歉略微偏离主题,但如果它是一个选项,我强烈建议使用ctypes而不是swig。 Here is a related question I asked previously in ctypes context: Passing a list of strings to from python/ctypes to C function expecting char ** 这是我之前在ctypes上下文中提到的一个相关问题: 将字符串列表从python / ctypes传递给C函数,期望char **

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM