簡體   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