Extension with factory

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • CarlosP

    Extension with factory

    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.createU nit in the C++ heap using the new
    operator. This instance should be wrapped as a CUnit and returned from
    CPackage_method s_createUnit.

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

    PyObject* CPackage_method s_createUnit(Py Object *self, PyObject *args) {
    char *name;
    if (!PyArg_ParseTu ple(args, "s", &name)) return NULL;
    Unit *unit = ((CPackage*)sel f)->cpackage->createUnit(nam e);
    return createCUnitFrom Unit(unit);
    }

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

Working...