Boost logo

Boost :

From: Peter.Bienstman_at_[hidden]
Date: 2001-07-27 08:57:47


Hi,

I'm still trying to find the best solution for the problem I already
mentioned in http://groups.yahoo.com/group/boost/message/14803

This is the code concerned:

#include <iostream>
#include "boost/python/class_builder.hpp"

using namespace boost::python;

struct Expression { Expression() {} };

struct Term
{
    Term() {}
    Term(const Expression&) {}
};

void f(const Term& t) {}

struct A { A(const Term&) {} };

BOOST_PYTHON_MODULE_INIT(convert)
{
  try
  {
  module_builder convert("convert");

  class_builder<Term> Term_(convert, "Term");
  Term_.def(constructor<>());
  Term_.def(constructor<const Expression&>());
  
  class_builder<Expression> Expression_(convert, "Expression");
  Expression_.def(constructor<>());

  convert.def(f , "f");

  class_builder<A> A_(convert, "A");
  A_.def(constructor<const Term&>());
  }
  catch(...) {}
}

>>>from convert import *
>>>e = Expression()
>>>f(Term(e))
>>>a = A(Term(e))

These work, but in my real-world application, the function signatures
are a lot more compilated (concatenated expressions using operators +
and *), and I don't want to burden my users with the need of
explicitly creating Terms from Expressions. The natural way of
writing would be

>>>f(e)
>>>a = A(e)

These give

TypeError: extension class 'Expression' is not convertible into 'Term'

So I set out to write a conversion function of my own:

BOOST_PYTHON_BEGIN_CONVERSION_NAMESPACE

PyObject* to_python(const Expression& e)
{
  return to_python(Term(e));
}

BOOST_PYTHON_END_CONVERSION_NAMESPACE

I was actually afraid that this would convert all my Expressions
straight to Terms, which is also not really what I want, but instead
this code changes nothing to the previous behaviour.

So, my question: can I add some code, either to my own code or to the
Boost library, to get the behaviour I want?

I started looking through the source, but with all these templates,
the flow of control is not really immediately obvious. Specifically,
when and from where is gen_extclass.py called? It seems to act like a
preprocessor, but due to my lack of understanding of the BPL big
picture, I currently don't see where it fits in.

Thanks,

Peter


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk