Trouble Passing Array of Strings (using Numeric) to C Extension Module

goetzie eric.goetzinger at seagate.com
Wed Sep 20 11:52:35 EDT 2006


I am using Python 2.4.1 and Numeric 23.8 and running on Windows XP.  I
am passing a Numeric array of strings (objects) to a C Extension module
using the following python code:

   import Numeric
   import TestDLL    # my C Extension Module

   a = Numeric.array(['foo', 'bar'], 'O' )
   print 'a =', a
   print 'type a[0] =', type(a[0])

   print TestDLL.StringArrayIn( a )

And here is the relevent code from my C Extension module:

   static PyObject * _StringArrayIn( PyObject *self, PyObject *args )
   {
      PyObject *pObject;  // input array
      PyArrayObject *pArray;  // contiguous array
      int iCount;
      int iStride;
      BOOL bString;

      if ( !PyArg_ParseTuple( args, "O", &pObject ) ) return NULL;

      if ( ( pArray = ( PyArrayObject * )PyArray_ContiguousFromObject(
pObject, PyArray_OBJECT, 1, 1 ) ) == NULL ) return NULL;

      iCount = pArray->dimensions[0];
      iStride = pArray->strides[0];

      bString = PyString_Check( ( PyObject * )( pArray->data ) );

      Py_DECREF( pArray );
      return Py_BuildValue( "iiO", iCount, iStride, PyBool_FromLong(
bString ) );
   }

   static PyMethodDef Methods[] =
   {
       { "StringArrayIn",  _StringArrayIn,  METH_VARARGS,   ""   },
       { NULL,             NULL,            0,              NULL } /*
Sentinel */
   };

This code produces the following output:

   a = [foo  bar ]
   type a[0] = <type 'str'>
   (2, 4, False)

The iCount and iStride values are as I expect (2 and 4 respectively),
but performing a PyString_Check on the first array element (or more
likely, what I think is the first array element) returns 'False'.

BTW, the output above is from running the Python interpreter from the
command line.  When I run this code in IDLE, I get a GPF if I don't
comment out the call to the PyString_Check function :-(

What am I doing wrong here?




More information about the Python-list mailing list