Click here to Skip to main content
14,240,716 members
Rate this:
Please Sign up or sign in to vote.
See more:
Hi,

I am new to python and I can't seem to send array's or struct's params from a python script to a c api. I have sent int's and strings ok.

I have managed to embed python into C that calls a python module script. I am also using SWIG. I will be using python unitttest to test calls to c api's.

I have had a good dig around and all the simple examples show params as int's or strings. There seems no examples of sending arrays or structs. How do I send from a python script a C array or struct to a c api via SWIG?

Is there a conversion? I tried sending "simple_array=array('i',[8,9])" Is it in the swig file? Any help appreciated!

/*simple_api.c*/
#include <stdio.h>
int Simple_api_Connector_UTF_SimplePointerArrayWriteTestFunc(int *pArray);

int Simple_api_Connector_UTF_SimplePointerArrayWriteTestFunc(int *pArray)
{
	printf("Simple_api_Connector_UTF_SimpleArrayWriteTestFunc: array byte 1:%x array byte 2: %x\n", pArray[1], pArray[2]);

	return 1;
}


-----------
/*simple_api.i*/
%module simple_api
int Simple_api_Connector_UTF_SimplePointerArrayWriteTestFunc(int *pArray);

-----------
#py_test_python.py
#!/usr/bin/env python
'''py_test_python.py - Python source designed to '''
'''demonstrate the use of python embedding in and out'''

def py_test_python_func():
    simple_api.Simple_api_Connector_UTF_ArrayWriteTestFunc([1,2])#<- tried loads here but always an error! 
Posted
Updated 8-Jun-15 15:55pm
v2
Rate this:
Please Sign up or sign in to vote.

Solution 1

There are helper functions in swig to handle arrays and vectors. It should make things easier to handle.
http://www.swig.org/Doc1.3/SWIG.html#SWIG_nn26[^]
http://www.swig.org/Doc2.0/SWIGDocumentation.html#Library_carrays[^]
   
Rate this:
Please Sign up or sign in to vote.

Solution 2

Thanks.

I have found a working typemap to convert the array variable in the SWIG interface (.i) file that works for writing an int array from the python script to the c api:

//type map for an input int array, this will calculate the length
%typemap(in) (const int length_in, int *int_in_array) 
{
  int i;
  if (!PyList_Check($input)) 
  {
    PyErr_SetString(PyExc_ValueError, "Expecting a list");
    return NULL;
  }
  $1 = PyList_Size($input);
  $2 = (int *) malloc(($1)*sizeof(int));
  for (i = 0; i < $1; i++) 
  {
    PyObject *s = PyList_GetItem($input,i);
    if (!PyInt_Check(s)) 
    {
        free($2);
        PyErr_SetString(PyExc_ValueError, "List items must be integers");
        return NULL;
    }
    $2[i] = PyInt_AsLong(s);
  }
}

And now I'm trying to read an array and read/write structs..
   
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100