Extension with factory

CarlosP carlosjosepita at yahoo.com.ar
Fri Dec 24 21:41:14 CET 2004


Hi!

I'm writing a C/C++ extension to python. I need to add two python types
which will be implemented as C++ classes. One of the classes acts as
(besides other functions) a factory for the other. Specifically, one is
Package and the other Unit, the createUnit method of Package lets you
create Units which in turn cannot be created independently (I mean from
"outside" the Package). The python object structures are defined as:

typedef struct {
PyObject_HEAD
Package* package;
} CPackage

typedef struct {
PyObject_HEAD
Unit* cunit;
} CUnit

And the python types structures are:

static PyTypeObject CPackage_type = {
....
}

static PyTypeObject CUnit_type = {
....
}

So I'm providing a tp_new implementation for CPackage_type as usual.
But I'm not sure how to cope with creation of CUnits. A Unit instance
should be created by Package.createUnit in the C++ heap using the new
operator. This instance should be wrapped as a CUnit and returned from
CPackage_methods_createUnit.

How should I do that? If I provided a tp_new for CUnit_type and invoked
it from CPackage_methods_createUnit, the tp_new would take PyObjects as
args and I would not be able to pass it the Unit* returned by
Package.createUnit which should be asigned to CUnit->cunit to be
wrapped as explained before. In pseudo code:

PyObject* CPackage_methods_createUnit(PyObject *self, PyObject *args) {
char *name;
if (!PyArg_ParseTuple(args, "s", &name)) return NULL;
Unit *unit = ((CPackage*)self)->cpackage->createUnit(name);
return createCUnitFromUnit(unit);
}

Reformulating the question, how should I implement createCUnitFromUnit?
Thank you in advance.
Regards,
Carlos




More information about the Python-list mailing list