[C++-sig] Re: Accessing instances of C++ objects in Python - Plus more

David Abrahams dave at boost-consulting.com
Fri Apr 2 21:23:27 CEST 2004

Mike Gonzales <mgonzale at digipen.edu> writes:

> Thank you for your input - I am incorporating it to make my code neater and
> more precise.  Anyway, I guess my question devolves to this: How do I
> access a C++ variable from python, and what steps do I need to take?

You can either expose it as a static member of a class using
def_readonly or def_readwrite:

                .def_readwrite("foo", &some_variable)

and access it as:

    >>> your_extension_module.X.foo
    <representation of foo>

or you can enter it in your module dictionary:

   scope().attr("foo") = object(boost::ref(some_variable));

and access it as:

    >>> your_extension_module.foo
    <representation of foo>

> The most obvious hack that I thought of was to try and manually
> insert the python-wrapped C++ variable into the main module's
> namespace dictionary; Is there a better way than that?


Dave Abrahams
Boost Consulting

More information about the Cplusplus-sig mailing list