[C++-sig] Boost.Python and Boost.Any

Kamal Mansouri kranar at hotmail.com
Thu Jul 2 21:50:06 CEST 2009


I am currently working on a way to convert boost::any to/from Python/C++.

So far the idea is that for any C++ type T exported to Python via Boost.Python,
you also register a function that converts an instance of boost::any storing a
value of type T to Python as well.

In other words, if you had a function f and exported it to Python as follows:

// C++ code:
boost::any f() {
  int x = 5;
  boost::any a = x;
  return a;

Then in Python it is possible to do this:

x = f()
print x

And it will print "5", the result of f() automatically gets converted into a Python
integer instead of an instance of boost::any storing an integer.

This part I got working, thankfully, my problem is doing the flip side, passing the value
5 from Python to a C++ function that takes a boost::any as a parameter and having
that boost::any store an int.

The problem with the solution I have now is that when I pass an arbitrary Python value
to a function taking a boost::any, the boost::any holds an instance of type PyObject*.

My AnyFromPython converter looks like this:

struct AnyFromPython {
  AnyFromPython() {
    converter::registry::push_back(&convertible, &construct, type_id<any>());

  static void* convertible(PyObject* value) {
    return value;

  static void construct(PyObject* value,
      converter::rvalue_from_python_stage1_data* data) {
    if(value == 0) {
    void* storage = ((converter::rvalue_from_python_storage<any>*)
    new (storage) any(value);
    data->convertible = storage;

The question is... is it possible to convert the parameter "value" into what it
would have otherwise been converted to in C++, and then take that result and
wrap it with a boost::any, as opposed to what it's doing now, which is just
wrapping a raw PyObject*.

If I could do this, then boost::any would work seamlessly with Python, and users
of my library would never need to know that boost::any is being used behind the
scenes in the C++ world.

Any help would be appreciated,

Attention all humans. We are your photos. Free us.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/cplusplus-sig/attachments/20090702/7f2acee9/attachment.htm>

More information about the Cplusplus-sig mailing list