[C++-sig] Re: question about using a python object from C++

David Abrahams dave at boost-consulting.com
Thu Jul 3 19:48:27 CEST 2003


Shi Sherebrin <shi at imaging.robarts.ca> writes:

> hello,
>
> I've spent a lot of time reading the Boost web pages, and I'm still
> mystified.  I have a class that I built in Python.  I want to use this
> class in C++.  From reading about Boost it seems to allow
> bidirectional operation, but I can't find a simple (or any) example of
> using C++ to access a Python object.  Could someone please point me in
> the right direction?

Getting ahold of the Python class object in C++ is your first problem.
The easiest way is to pass it as an argument to a wrapped C++
function:

        void f(boost::python::object python_class)
        {
            ...
        }

Now you can construct an instance of the class just as you would in
Python:

        void f(object python_class)
        {
            object instance = python_class(3, "hello", 22.5);
            instance.Run(42)
            instance.Shutdown();
            ...
        }

    >>> class Foo:
    ...     def __init__(count, message, rating):
    ...         self.count = count
    ...         self.message = message
    ...         self.rating = rating
    ...
    >>> import my_extension
    >>> my_extension.f(Foo)

If you can't pass the class into your C++ function, you'll have to
use the Python 'C' API to access the module in which you've created
it and pull out the class attribute:

    // Retrieve the main module
    // Have to use the Python 'C' API for this part unfortunately.
    object main_module(
        python::handle<>(
            python::borrowed(PyImport_AddModule("__main__")) ));

    // get __main__.Foo
    object Foo = main_module.attr("Foo");

    // instantiate one
    object inst = Foo(3, "hello", 22.5);
    
    // use it.
    inst.Run(42)
    inst.Shutdown();

-- 
Dave Abrahams
Boost Consulting
www.boost-consulting.com





More information about the Cplusplus-sig mailing list