diff --git a/extclass_demo.cpp b/extclass_demo.cpp index dd6c13f5..8eaccab2 100644 --- a/extclass_demo.cpp +++ b/extclass_demo.cpp @@ -8,6 +8,7 @@ #include "extclass_demo.h" #include "class_wrapper.h" #include // used for portability on broken compilers +#include namespace extclass_demo { @@ -290,6 +291,50 @@ long range_hash(const Range& r) return r.m_start * 123 + r.m_finish; } +typedef boost::rational Ratio; + +py::String ratio_str(const Ratio& r) +{ + char buf[200]; + + if (r.denominator() == 1) + sprintf(buf, "%d", r.numerator()); + else + sprintf(buf, "%d/%d", r.numerator(), r.denominator()); + + return py::String(buf); +} + +py::String ratio_repr(const Ratio& r) +{ + char buf[200]; + sprintf(buf, "Rational(%d, %d)", r.numerator(), r.denominator()); + return py::String(buf); +} + +py::Tuple ratio_coerce(const Ratio& r1, int r2) +{ + return py::Tuple(r1, Ratio(r2)); +} + +// The most reliable way, across compilers, to grab the particular abs function +// we're interested in. +Ratio ratio_abs(const Ratio& r) +{ + return boost::abs(r); +} + +// An experiment, to be integrated into the py_cpp library at some point. +template +struct StandardOps +{ + static T add(const T& x, const T& y) { return x + y; } + static T sub(const T& x, const T& y) { return x - y; } + static T mul(const T& x, const T& y) { return x * y; } + static T div(const T& x, const T& y) { return x / y; } + static T cmp(const T& x, const T& y) { return std::less()(x, y) ? -1 : std::less()(y, x) ? 1 : 0; } +}; + void init_module(py::Module& m) { m.add(new Foo::PythonClass); @@ -309,6 +354,21 @@ void init_module(py::Module& m) m.def(first_string, "first_string"); m.def(second_string, "second_string"); + // This shows the wrapping of a 3rd-party numeric type. + py::ClassWrapper > rational(m, "Rational"); + rational.def(py::Constructor()); + rational.def(py::Constructor()); + rational.def(py::Constructor<>()); + rational.def(StandardOps::add, "__add__"); + rational.def(StandardOps::sub, "__sub__"); + rational.def(StandardOps::mul, "__mul__"); + rational.def(StandardOps::div, "__div__"); + rational.def(StandardOps::cmp, "__cmp__"); + rational.def(ratio_coerce, "__coerce__"); + rational.def(ratio_str, "__str__"); + rational.def(ratio_repr, "__repr__"); + rational.def(ratio_abs, "__abs__"); + py::ClassWrapper range(m, "Range"); range.def(py::Constructor()); range.def(py::Constructor()); @@ -321,6 +381,7 @@ void init_module(py::Module& m) range.def(&range_hash, "__hash__"); range.def_readonly(&Range::m_start, "start"); range.def_readonly(&Range::m_finish, "finish"); + } void init_module()