[C++-sig] Re: instantiating python objects within C++
David Abrahams
dave at boost-consulting.com
Wed May 28 12:54:37 CEST 2003
Stefan Seefeld <seefeld at sympatico.ca> writes:
> David Abrahams wrote:
>
>> The Boost.Python shared library has a converter registry where all of
>> this information is stored.
>
> ok, this seems really to be the key. How does this work ?
You can "use the source, Luke" if you want to know how it's
implemented ;-)
> I'm a bit confused, as conceptually the lines
>
> BOOST_PYTHON_MODULE(Sandbox)
> {
> python::class_<Base> base_type("Base");
> //...
> }
>
> create a type 'Sandbox.Base', i.e. the equivalent in C++ would be
> something like 'Sandbox::Base'. However, 'Sandbox' isn't a type,
...right...
> so I wonder how I can access the above type object from inside C++.
I don't see what Sandbox being a type or a module has to do with it.
A Python type is just a kind of Python object. When the class_< ... >
instantiation creates it, it holds onto it as well.
> Your example at the bottom of
> http://www.boost.org/libs/python/doc/tutorial/doc/derived_object_types.html
> hints a bit at how to instantiate such type objects, but I fail
> to see how I could do that from within a different 'scope'.
I don't know what you mean by 'scope' here. Can't you spell out
explicitly what it is you'd like to do? Code helps.
> What I'm really pondering about now is how to compare types, i.e.
> if I'v obtained a type from a python script, and I want to test
> whether this type derives from 'Sandbox.Base':
>
> from Sandbox import *
> class Derived(Base):
> def foobar(self): pass
>
> I should be able to take the python::object that is the
> (wrapper around the) python type, and compare it with the 'base_type'
> from the above snippet, i.e. doing something like
>
> python::handle<> result(PyRun_File(fp, const_cast<char *>(file.c_str()),
> Py_file_input,
> globals.ptr(), globals.ptr()));
> python::object derived_type = globals["Derived"];
>
> I want to compare 'derived_type' with 'base_type', for example using
>
> Py_IsSubclass(derived_type.ptr(), base_type.ptr())
>
> But how can I access 'base_type' ? It's a local variable in the
> scope of 'BOOST_PYTHON_MODULE(Sandbox), or is it ?
Of course it is, the way you've written it. You can always keep a
python::object 'save_base_type' around and assign into it:
save_base_type = base_type;
A more-elegant way to hang onto it is:
python::object base_type;
BOOST_PYTHON_MODULE(Sandbox)
{
base_type
= python::class_<Base>("Base")
.def(...)
...
;
}
--
Dave Abrahams
Boost Consulting
www.boost-consulting.com
More information about the Cplusplus-sig
mailing list