member array in c passed to python?

W

William Hanlon

Hi,

I would like to use the Python C API to use python to access functions
originally written in C. The objects that I would like to pass to python
have multi-dimensional arrays.

How do I include arrays as object member? And how is it declared in the
PyMemberDef array?

If you can not use C arrays, I thought perhaps then I should use Python
tuples or lists, but I don't see how to fill the tuple from the
multi-dimensional arrays. Does anyone have an example of this?

Thanks,
William Hanlon
 
A

Alex Martelli

William said:
Hi,

I would like to use the Python C API to use python to access functions
originally written in C. The objects that I would like to pass to python
have multi-dimensional arrays.

How do I include arrays as object member? And how is it declared in the
PyMemberDef array?

You can, if you wish, construct and expose a new "array" type from
within your extension -- or reuse those already constructed for you
by the Numeric package.

If you can not use C arrays, I thought perhaps then I should use Python
tuples or lists, but I don't see how to fill the tuple from the
multi-dimensional arrays. Does anyone have an example of this?

You have to know the number of dimensions and proceed accordingly,
For example, for a 2-dimensional array of integers you could do
something like:

PyObject*
array_to_list_2d(int **array, int N, int M)
{
PyObject * temp;
PyObject * result = PyList_New(N);
for(i = 0; i < N; i++) {
PyList_SET_ITEM(result, i, temp = PyList_NEW(M));
for(j = 0; j < M; j++)
PyList_SET_ITEM(temp, j, PyInt_FromLong(array[j]));
}
return result;
}

However, this does need a lot of data copying and object allocation,
which you might obviate if you were to use your own data type (or
reuse Numeric's) to wrap your existing arrays.


Alex
 

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

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,021
Latest member
AkilahJaim

Latest Threads

Top