Embeding python i C++

Dave Kuhlman dkuhlman at rexx.com
Sun Jul 7 19:43:21 EDT 2002


Jardar wrote:

> I have just started looking at using python as a
> scriptinglanguage. I have successfully created extensions to the
> python interpretter so there is noe problem calling C++
> functionality from python (used SWIG for creating wrappers). I
> have also sucessfully called a python function from C++. The
> problems starts when I want to pass a C++ object to a python
> function. Passing simple strings og intergers are easy, but I can
> find out how to pass whole objects. Can anybody help me out here.
> 
> Thanks in advance
> 
> Jardar

What kind of object?  If it is a C++ array, then convert it to a 
tuple or a list using the functions in the "Python/C API Reference 
Manual".  For example, see

    http://www.python.org/doc/current/api/tupleObjects.html

and

    http://www.python.org/doc/current/api/listObjects.html

Similar C APIs are available for strings, longs, dictionaries, etc.

In short, you can only pass *Python* objects from your C++ code to 
your Python code.

If none of the existing Python types is what you want, it is also 
possible to implement new Python types in C/C++.  Then you can, in 
your C/C++ code, create instances of your new type and pass them to 
your Python code.  See "Defining New Types":

    http://www.python.org/doc/current/api/newTypes.html

That's a bit more complex.  But, if it is what you want, you will 
find a pattern for doing so in the source code distribution of 
Python.  Look at Python-2.2.1/Objects/xxobject.c.

You might also consider implementing a class in Python, passing the 
class object to your C++ code, creating an instance of the class in 
C++, then passing the instance back to your Python code.  Whew!  
Actually, I don't know how to do this.  But, it seems do-able and 
some of the needed functionality is described in "7.5.2 Instance 
Objects" at:

    http://www.python.org/doc/current/api/instanceObjects.html

After your C/C++ code has created an instance of the Python class, 
here is a bit of C code for calling a method on that instance:


    char * name;
    /* Does the instance have an attribute "endElement"? */
    if (PyObject_HasAttrString(instance, "endElement"))
    {
        name = "some value for Python";
        /* Call the method, passing a string argument. */
        result = PyObject_CallMethod(instance, "endElement", "s",   
               name);
        if (PyErr_Occurred())
        {
            PyErr_Print();
        } /* if */
    } /* if */


Hope this helps.

  - Dave


-- 
Dave Kuhlman
dkuhlman at rexx.com
http://www.rexx.com/~dkuhlman




More information about the Python-list mailing list