使用SWIG从Python向C传递和数组参数

使用SWIG从Python向C传递和数组参数,python,c,arrays,numpy,swig,Python,C,Arrays,Numpy,Swig,我第一次使用SWIG+Python+C,在将数组从Python传递到C时遇到了问题 这是C语言中的函数签名 my_setup(char * my_string, int my_count, int my_types[], double my_rate, int my_mode); 我想从Python中调用这个C函数,如下所示 my_array = [1, 2, 3, 4, 5, 6] my_setup("My string", 6, my_array, 50, 0) 但是我不知道如何构造数组

我第一次使用SWIG+Python+C,在将数组从Python传递到C时遇到了问题

这是C语言中的函数签名

my_setup(char * my_string, int my_count, int my_types[], double my_rate, int my_mode);
我想从Python中调用这个C函数,如下所示

my_array = [1, 2, 3, 4, 5, 6]
my_setup("My string", 6, my_array, 50, 0)
但是我不知道如何构造数组
myu数组
。我得到的错误是

Traceback (most recent call last):
  File "test_script.py", line 9, in <module>
    r = my_library.my_setup("My string", 6, my_types, 50, 0)
TypeError: in method 'my_setup', argument 3 of type 'int []'
回溯(最近一次呼叫最后一次):
文件“test_script.py”,第9行,在
r=我的_库。我的_设置(“我的字符串”,6,我的_类型,50,0)
TypeError:在方法“my_setup”中,参数3的类型为“int[]”
我尝试使用and失败

我希望有人能帮我传递一个数组作为函数
my\u setup
的第三个参数


还有,这是我的第一篇堆栈溢出帖子

解析
my_setup()
中的Python列表,而不是尝试在SWIG
.i
文件中翻译它。改变

my_setup(char * my_string, int my_count, int my_types[], double my_rate, int my_mode);

在我的设置中

    int *array = NULL;
    if ( PyList_Check( int_list ) )
    {
        int nInts = PyList_Size( int_list );
        array = malloc( nInts * sizeof( *array ) );
        for ( int ii = 0; ii < nInts; ii++ )
        {
            PyObject *oo = PyList_GetItem( int_list, ii );
            if ( PyInt_Check( oo ) )
            {
                array[ ii ] = ( int ) PyInt_AsLong( oo );
            }
        }
    }
int*array=NULL;
if(PyList_检查(int_列表))
{
int nInts=PyList_大小(int_列表);
数组=malloc(nInts*sizeof(*数组));
用于(int ii=0;ii
您必须添加错误检查。在使用SWIG时,从C中始终将
PyObject*
返回到Python。这样,您就可以使用
PyErr_SetString()
并返回NULL来抛出异常

    int *array = NULL;
    if ( PyList_Check( int_list ) )
    {
        int nInts = PyList_Size( int_list );
        array = malloc( nInts * sizeof( *array ) );
        for ( int ii = 0; ii < nInts; ii++ )
        {
            PyObject *oo = PyList_GetItem( int_list, ii );
            if ( PyInt_Check( oo ) )
            {
                array[ ii ] = ( int ) PyInt_AsLong( oo );
            }
        }
    }