简体   繁体   English

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

[英]Passing and array argument to C from Python using SWIG

I am using SWIG + Python + C for the first time, and I am having trouble passing an array from Python to C. 我是第一次使用SWIG + Python + C,我在将数组从Python传递给C时遇到了问题。

Here is a function signature in C. 这是C中的函数签名。

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

I would like to call this C function from Python as follows 我想从Python中调用这个C函数,如下所示

my_array = [1, 2, 3, 4, 5, 6]
my_setup("My string", 6, my_array, 50, 0)

but I do not know how to construct the array my_array . 但我不知道如何构造数组my_array The error I am getting is 我得到的错误是

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

I have tried unsuccessfully to use the SWIG interface file for numpy and ctypes . 我尝试将SWIG接口文件用于numpyctypes但未成功

I hope someone can help me pass an array as the third argument of the function my_setup . 我希望有人可以帮助我传递一个数组作为函数my_setup的第三个参数。

Also, this is my first stack overflow post! 另外,这是我的第一个堆栈溢出帖子!

Parse the Python list inside my_setup() instead of trying to translate it in your SWIG .i file. 解析my_setup()的Python列表,而不是尝试在SWIG .i文件中翻译它。 Change 更改

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

to

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

and in my_setup 并在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 );
            }
        }
    }

You'll have to add error checking. 您必须添加错误检查。 And from C, always return a PyObject * back to Python when you're using SWIG. 从C开始,当您使用SWIG时,总是将PyObject *返回给Python。 That way, you can use PyErr_SetString() and return NULL to toss an exception. 这样,您可以使用PyErr_SetString()并返回NULL以抛出异常。

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

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