[C++-sig] Re: instantiating python objects within C++
David Abrahams
dave at boost-consulting.com
Tue May 27 14:51:25 CEST 2003
Stefan Seefeld <seefeld at sympatico.ca> writes:
> 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.
It's not really embedding-specific, but as I said before, we'd be
very happy to consider a doc patch from you.
> 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...
my_module.attr("object") = foo_wrapper; // equivalent
> 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"]);
Why are you using extract<> here? Isn't main_namespace a
boost::python::object whose operator[] returns an object?
> callable(boost::reference_wrapper<Foo>(foo));
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
This is long-winded, and should be spelt:
boost::ref(foo)
instead.
>
> 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*.
I still don't know what's going on because you've not shown a
definition for the name 'foo'.
> That's what I was referring to with 'the python interpreter'. Would
> 'python runtime' be a better term ?
Maybe.
>> 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.
The Boost.Python shared library has a converter registry where all of
this information is stored.
HTH,
--
Dave Abrahams
Boost Consulting
www.boost-consulting.com
More information about the Cplusplus-sig
mailing list