Embed extended Python

Bjorn Pettersen BPettersen at NAREX.com
Fri Sep 13 21:29:14 CEST 2002

> From: Mathieu Tremblay [mailto:mtremblay at golemlabs.com] 
> Hello, 
>    I am quite new to Python and I'd like to embed extended python. 
> The problem is that the documentation I can find on the 
> internet is always related to C standard types and not to C++ objects.


It isn't clear to me exactly what you're having problems with so I'll
just give you the general overview of what you need to do... First you
need to initialize Python and your extension modules. In this case I'm
using SIP to wrap C++ (hence the call to initlibsip), and my wrapped
module is libnrxc.dll).

    PyInitializer::PyInitializer() {
        // Initialize Python
        // initialize SIP (the wrapper generator) library

        // initialize the Narex library

        PyObject* mainmod = PyImport_AddModule("__main__");
        m_namespace = PyModule_GetDict(mainmod);
        // make sure the nrx module is loaded
        try {
            PyObject* m_result = 
                    "import nrx\n",    // has to end in \n

            if (m_result == NULL) {
                // getTraceback() returns the traceback as a
                throw new NException(getTraceback().c_str(), N_EX_NULL);
            } else {
        } catch(NException *e) {
            std::cout << e->getMessageText();
After all that you should be able to call into your C++ module:

    PyObject* res = PyRun_String("nrx.CWheel()", Py_eval_input,
m_namespace, m_namespace);    
res is now your C++ instance wrapped in a PyObject. To get back the C++
object, you'll have to call a function from your wrapping library that
will do that for you, e.g. for SIP:

    int error;
    CWheel = (CWheel*)sipConvertToCpp(res, sipClass_CWheel, &error);
I haven't used swig in a while, so I don't know what the swig call is,
but you get the idea...

When you want to go the other way (have c++ object, need PyObject),
there is a similar call:

    PyObject* val = sipMapCppToSelf(&myWheel, sipClass_CWheel);

-- bjorn

More information about the Python-list mailing list