call python from c -> pass and return arrays/lists

P

Pieter

Hi all,

I'm trying to call a python function from c. I need to pass an
2D-array to python and the python function returns a 2D-list back to
c. I googled arround and I found how to pass ints/strings/... back and
forth, but didn't find anything on passing arrays.

For an int it's as simple as this:

PyArg_Parse(ret,"i#", &my_long);

But I hacve no idea how to parse python lists to a c-array?

thanks a lot,

Pieter
 
D

Diez B. Roggisch

Pieter said:
Hi all,

I'm trying to call a python function from c. I need to pass an
2D-array to python and the python function returns a 2D-list back to
c. I googled arround and I found how to pass ints/strings/... back and
forth, but didn't find anything on passing arrays.

For an int it's as simple as this:

PyArg_Parse(ret,"i#", &my_long);

But I hacve no idea how to parse python lists to a c-array?

You return a list, parse that as object, and then work with the
sequence-protocol on them.

UNTESTED:

PyArg_Parse(ret,"o", &the_list);
if(PySequence_Check(the_list) {
int size = PySequence_Size(the_list);
int *result = malloc(sizof(int) * size);
for(int i = 0; i < size; i++) {
PyObject *item = PySequence_GetItem(the_list, i);
if(PyInt_Check(item)) {
result = PyInt_AsLong(item);
} else {
return NULL;
}
}



Diez
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,994
Messages
2,570,223
Members
46,815
Latest member
treekmostly22

Latest Threads

Top