[C++-sig] Re: instantiating python objects within C++

Stefan Seefeld seefeld at sympatico.ca
Tue May 27 01:53:29 CEST 2003

David Abrahams wrote:

>>The python interpreter then figures out that it should create the so
>>defined wrapper object and wrap it around my existing foo instance.
> It's not really clear to me just what you mean.

What I understood well from your tutorial was how to define python
type objects (wrappers around C++ classes) and how to inject them into
a given module. What I was missing was how to instantiate python
objects of these types. Once I'v seen it it appears quite 'natural' and
it was in fact such a simple construct that I was expecting. I guess
a simple example near the 'embedding' section in the tutorial would
clarify things a lot.

What I'm doing right now is this:

class Foo {/*...*/};

python::class_<Foo> foo_type("Foo");
      foo_type.add_property("value", &Foo::get_value, &Foo::set_value);

      python::object foo_wrapper = foo_type();
      main_namespace["object"] = foo_wrapper; // globale object, used later...

      FILE *fp = fopen("script.py", "r");
      python::handle<> result2(PyRun_File(fp, "script.py", Py_file_input,
                      main_namespace.ptr(), main_namespace.ptr()));

      python::object callable = python::extract<python::object>(main_namespace["set"]);

What I was missing here (and still don't really understand) is how the
definition of 'foo_type' above somewhere registers itself such that the call in the
last line will find it *at runtime*. That's what I was referring to with 'the python
interpreter'. Would 'python runtime' be a better term ?

> Hmm.  Well, yeah, a description of the conversion mechanisms would be
> good to have.

Absolutely, I guess that was the piece of the puzzle that I was missing.

Best regards,

More information about the Cplusplus-sig mailing list