Extension with factory

C

CarlosP

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
 

Ask a Question

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

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top