member array in c passed to python?

Discussion in 'Python' started by William Hanlon, Aug 4, 2003.

  1. 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
     
    William Hanlon, Aug 4, 2003
    #1
    1. Advertising

  2. 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[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
     
    Alex Martelli, Aug 4, 2003
    #2
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. dee
    Replies:
    9
    Views:
    524
    Joseph Byrns
    Apr 15, 2005
  2. Anand
    Replies:
    2
    Views:
    915
    Anand
    Sep 11, 2003
  3. James Stroud
    Replies:
    3
    Views:
    312
    James Stroud
    May 7, 2005
  4. Sandra-24
    Replies:
    2
    Views:
    290
    Sandra-24
    Sep 4, 2006
  5. Belebele
    Replies:
    6
    Views:
    346
    Pierre Barbier de Reuille
    Aug 14, 2006
Loading...

Share This Page