wrapping a C++ class

Enrico Ng ng at fnmail.com
Thu Jun 14 17:24:52 EDT 2001


I am trying to wrap a simple C++ class like this:

 class mymath {
 int x, y;
public:
  void set_values(int a, int b) {x=a;y=b;}
  int add(void) {return (x+y);}};

The thing is, I'm not sure how to wrap this.  I am assuming the self is the
pointer for the class that gets passed.  But I dont think I am casting it
correctly here.
Here is my wrapper code:

#include "Python.h"
#include "test.cpp"

extern "C" {
static PyObject *wrap_add(PyObject *self, PyObject *args) {
  PyObject *Pyresult;
  mymath *arg0 = (mymath*) self;
  if (!PyArg_ParseTuple(args, ":add")) return NULL;
  Pyresult = PyInt_FromLong((long)arg0->add());
  return Pyresult;
}

static PyObject *wrap_set_values(PyObject *self, PyObject *args) {
  mymath *arg0 = (mymath*) self;
  int arg1;                   file://var for argument
  int arg2;                   file://var for argument
  if (!PyArg_ParseTuple(args, "ii:set_values",&arg1,&arg2)) return NULL;
  arg0->set_values(arg1,arg2);
  Py_INCREF(Py_None);
  return Py_None;
}

static PyMethodDef testMethods[] = {
         { "add", wrap_add, METH_VARARGS },
         { "set_values", wrap_set_values, METH_VARARGS },
         { NULL, NULL }
};

void inittest() {Py_InitModule("test", testMethods);}
    }


--
Enrico Ng <enrico at fnal.gov>
Fermilab - WH 13X





More information about the Python-list mailing list