William Hanlon wrote:
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[i][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