Embed extended Python

Bjorn Pettersen BPettersen at NAREX.com
Fri Sep 13 15:29:14 EDT 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.

[snip]

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
        Py_Initialize();
        
        // initialize SIP (the wrapper generator) library
        initlibsip();

        // initialize the Narex library
        initlibnrxc();

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

            if (m_result == NULL) {
                // getTraceback() returns the traceback as a
std::string.
                throw new NException(getTraceback().c_str(), N_EX_NULL);
            } else {
                Py_DECREF(m_result);
            }
        } 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);

hth,
-- bjorn




More information about the Python-list mailing list