Boost logo

Boost :

From: David Abrahams (dave_at_[hidden])
Date: 2002-11-07 08:27:10


¿ÂÃÍ <k.meng_at_[hidden]> writes:

> Hi:
>
> I'm now use the boost.python,and want to write my own converter.
> In the last version,I can write like this:
>
> #include <boost/python/class_builder.hpp>
> namespace python = boost::python;
> BOOST_PYTHON_BEGIN_CONVERSION_NAMESPACE
> inline AsnInt from_python(PyObject* p, python::type<const AsnInt&>)
> {
> return AsnInt(from_python(p, python::type<int>()));
> }
> inline AsnInt from_python(PyObject* p, python::type<AsnInt>)
> {
> return from_python(p, python::type<const AsnInt&>());
> }
> inline PyObject* to_python(const AsnInt& ai)
> {
> return PyInt_FromLong((AsnIntType)ai);
> }
> BOOST_PYTHON_END_CONVERSION_NAMESPACE
>
>
> In this new version, what can I do for the same work? Please give me some examples,
> Thank you very much!

This is unsupported interface in v2, because it will probably change a
bit before it becomes supported in the next major release (to make it
easier), but here goes:

  // Untested!!
  PyObject* AsnInt_to_python(void const* x)
  {
      AsnInt const& ai = *(AsnInt const*)x;
      return PyInt_FromLong((AsnIntType)ai);
  }

  struct AsnInt_rvalue_from_python
  {
      static void* convertible(PyObject* obj)
      {
          return (PyInt_Check(obj) || PyLong_Check(obj))
              ? obj : 0;
      }

      static void construct(PyObject* obj, rvalue_from_python_stage1_data* data)
      {
          // Get the (intermediate) source object
          unaryfunc creator = &obj->ob_type->tp_as_number->nb_int;
          handle<> intermediate(creator(obj));

          // Get the location in which to construct
          void* storage = ((rvalue_from_python_storage<AsnInt>*)data)->storage.bytes;
          new (storage) AsnInt(PyInt_As_Long(intermediate.get()));

          // record successful construction
          data->convertible = storage;
      }
  };

    ...

    boost::python::converter::registry::insert(
            AsnInt_to_python, type_id<AsnInt>());
    boost::python::converter::registry::insert(
            AsnInt_rvalue_from_python::convertible
            , AsnInt_rvalue_from_python::construct
            , type_id<AsnInt>());

-- 
                    David Abrahams
dave_at_[hidden] * http://www.boost-consulting.com

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