Reputation: 31
I am using SWIG + Python + C for the first time, and I am having trouble passing an array from Python to C.
Here is a function signature in 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
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
. 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.
I hope someone can help me pass an array as the third argument of the function my_setup
.
Also, this is my first stack overflow post!
Upvotes: 3
Views: 1214
Reputation: 1
Parse the Python list inside my_setup()
instead of trying to translate it in your SWIG .i
file. 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
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. That way, you can use PyErr_SetString()
and return NULL to toss an exception.
Upvotes: 1