[C++-sig] embedding an extended python module

Daniel Lawson daniel at wand.net.nz
Wed Jan 12 10:40:59 CET 2005

Hi there,

I'm using Boost:Python to extend Python, in order to provide access to 
some C++ classes I have written. This is working fine - I can load the 
resulting module in Python, instantiate the classes exported via Boost, 
and manipulate them and so on.

typedef std::map<std::string ,Attr *> attrmap;
class Node {
    std::string name;
    attrmap attrs;
    Node(std::string name);
    void addAttr(std::string key, int val);
    void getAttr(std::string key);

    using namespace boost::python;
        .def("addAttr", &Node::addAttr)
        .def("getAttr", &Node::getAttr)

I also have a program which has embedded Python in it. This program can 
be passed the names of some python files, which it will load and import 
specific symbols from:

    filtername = "filter.py";
    pName = PyString_FromString(filtermod);
    pfilterhnd = PyImport_Import(pName);
    pDict = PyModule_GetDict(pfilterhnd);
    pfilter = PyDict_GetItemString(pDict, "filter");

And so on. Later on, I then call this filter function:

    pName = PyString_FromString("name");
    pNode = PyString_FromString("node");
    pArgs = PyTuple_New(2);
    PyTuple_SetItem(pArgs, 0, pName);
    PyTuple_SetItem(pArgs, 1, pNode);
    pRetVal = PyObject_CallObject(phandler,pArgs);

Where pArgs is a tuple of arguments.

This works fine, as long as I only pass basic Python types to the 
function - eg, strings (PyString_FromString), longs (PyInt_FromLong) etc.

However, I want to be able to pass, into the embedded python, instances 
(pointers to, actually) the classes which I have exported via Boost. 
More so, I want the python module I loaded above to be able to modify 
the datastructure, and have the calling program make use of this.

I've imported the appropriate modules into the python interpreter 
embedded into my C++ program.

 From what I've read, within the calling C++ program I need to convert 
(or wrap) the instance of my Node class into a PyObject *. Once I've 
done that, I can use PyObject_Callfunction or similar to call the python 
function, passing my Node class into it. Once in there, python will use 
the boost-extended module to access it.

I've been reading mailing lists all day, it seems like this should be 
very possible, I'm just totally stumped as to how. There's plenty of 
examples for embedding python into a C/C++ program, and there's plenty 
of examples for extending python with a C/C++ extension, but there don't 
seem to be so many which put the two together.



More information about the Cplusplus-sig mailing list