Obtaining the PyObject * of a class

Cooper, Andrew ACooper at cimtek.com
Mon Mar 10 11:54:37 EDT 2008


I',m currently using SWIG to generate a python interface to a C DLL.

I'm new to the Python C API and have a question that has been stumping
me for the last week.
As part of the wrapper process I want to hide some of the complexity
with dealing with handles using a python class.

But the problem I have is I don't know how to get the PyObject* that
refers to the class Pin that I have defined in the %pythoncode section

Here is a cut down version of the interface file

%module example

typedef long pin;
typedef unsigned short ushort;

ushort wkDefinePin(char *, char *, pin *OUTPUT);

%pythoncode
{
  class Pin(object):
    def __init__(self, name, tic):
      self.handle = wkDefinePin(name,tic)[1]
      return     
}	    



%typemap(in) (pin tp) 
{
  //
  // TODO: really need to change this to IsInstance type code
  //
  if(strcmp($input->ob_type->tp_name,"Pin") == 0)
  {
    $1 = PyInt_AsLong(PyObject_GetAttrString($input,"handle"));
  }
  else
  {
    PyErr_SetString(PyExc_TypeError,"arg must be type Pin");
    return NULL;
  }
}

%typemap(in) (int nCnt_tp, pin *tp) 
{
  /* Check if is a list */
  if (PyList_Check($input)) 
  {
    int i;
    $1 = PyList_Size($input);
    $2 = (pin *) malloc(($1) * sizeof(pin));
    for (i = 0; i < $1; i++) 
    {
      //
      // TODO: really need to change this to IsInstance type code
      //
      PyObject *o = PyList_GetItem($input,i);
      if (strcmp(o->ob_type->tp_name, "Pin") == 0)
      {
        $2[i] = PyInt_AsLong(PyObject_GetAttrString(o,"handle"));
      }
      else 
      {
        PyErr_SetString(PyExc_TypeError,"list must contain Pins");
        free($2);
        return NULL;
      }
    }
    $2[i] = 0;
  } 
  else 
  {
    PyErr_SetString(PyExc_TypeError,"not a list");
    return NULL;
  }
}




More information about the Python-list mailing list