繁体   English   中英

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

[英]Passing and array argument to C from Python using 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)

但我不知道如何构造数组my_array 我得到的错误是

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 []'

我尝试将SWIG接口文件用于numpyctypes但未成功

我希望有人可以帮助我传递一个数组作为函数my_setup的第三个参数。

另外,这是我的第一个堆栈溢出帖子!

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

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

my_setup(char * my_string, int my_count, PyObject *int_list, double my_rate, int my_mode);

并在my_setup中

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

您必须添加错误检查。 从C开始,当您使用SWIG时,总是将PyObject *返回给Python。 这样,您可以使用PyErr_SetString()并返回NULL以抛出异常。

暂无
暂无

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

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