[C++-sig] Wrapping a function that takes class type, such as type_info
Jim Bosch
talljimbo at gmail.com
Thu Feb 23 17:03:18 CET 2012
On 02/23/2012 02:31 AM, Adam Preble wrote:
> I think I need to ask a better question here, so I'm coming back here with
> an adjusted situation. I've found I can't get Python to bind up to
> prototypes for stuff taking std::type_info or boost::type_info. I suppose
> I should be surprised if it actually did. I'm thinking--what if I have a
> Python implementation of an interface I defined in C++? It would be really
> odd if that would even be compatible with type_info in any way. I am
> thinking type_info is not the way to go, but I see some code in Boost
> dealing with PyType.
>
Glad you sent this; I was about to reply to your last with something
that probably wouldn't have been very helpful, for the reasons you've
already noted yourself.
> I figure what I need instead is a method that types something else than
> type_info, but what I need is a mystery. For giggles, I just tried to take
> a PyObject* and pass in whatever. if I give it from Python type(Foo) then
> I think I get a PyType. I see some stuff in Boost source code about
> working with these. I'm wondering, is there any helpers for this? Or any
> idea at all what to do?
>
You can probably find out a lot from just looking at the Python C API
reference documentation for type objects. You'll need to use that
directly for a lot of your interaction with them, because there's no
Boost.Python wrapper (like there is for, say, tuple or str).
The main place you'll see them in Boost.Python is that this is actually
what a boost::python::class_ object holds under the hood; you can assign
that to a boost::python::object to get the type object without having to
carry around all the template parameters.
> I suppose the overall situation is this: imagine I have a container of
> pointers referencing some interface. The container contains potentially
> both C++ and Python implementations. All implementations are exposed in
> Python. Is there a way I could pass in some kind of type information and
> be able to positively identify if something in that container matches the
> type?
>
Yes, as long as:
- You can do the checking with a Python function that operates on type
objects, like isinstance and issubclass (or their C API equivalents,
PyObject_IsInstance and PyObject_IsSubclass).
- You are content with looking up a PyTypeObject* given a C++ type_info,
and not the other way around; you can use
boost::python::converter::registry::lookup to find the PyTypeObject for
a Boost.Python-wrapped class. That's deep in the bowels of
Boost.Python's internals - see converter/registry.hpp and
converter/registration.hpp to learn more - but it's quite usable.
Jim
More information about the Cplusplus-sig
mailing list