如何用SWIG将C数组转换成Python元组或列表?

2024-04-23 15:55:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在开发一个C++/Python库项目,它在将C++代码转换为Python库时使用SWIG。在C++标题中,我有一些全局常量值如下。在

const int V0 = 0;
const int V1 = 1;
const int V2 = 2;
const int V3 = 3;
const int V[4] = {V0, V1, V2, V3};

我可以直接从Python使用V0到V3,但是不能访问V中的条目。在

^{pr2}$

有人能告诉我如何自动将V转换成Python元组或列表吗?我应该在.i文件中做什么?在


Tags: 项目代码标题条目v3全局v2swig
2条回答

如果不想创建类型映射,可以使用swig库carrays.i访问C-type数组中的条目。在

你的.i文件应该是:

%{
#include "myheader.h"
%}

%include "carrays.i"
%array_functions(int,intArray)

%include "myheader.h"

然后您可以使用以下命令访问python中的mylibrary.V[0]:

^{pr2}$

下面的宏确实有效。在

%{
#include "myheader.h"
%}

%define ARRAY_TO_LIST(type, name)
%typemap(varout) type name[ANY] {
  $result = PyList_New($1_dim0);
  for(int i = 0; i < $1_dim0; i++) {
    PyList_SetItem($result, i, PyInt_FromLong($1[i]));
  } // i
}
%enddef

ARRAY_TO_LIST(int, V)

%include "myheader.h"

相关问题 更多 >