make annotations sequenceable from python
[mussa.git] / py / annotations.cpp
1 #include <boost/iterator.hpp>
2
3 #include <boost/python.hpp>
4 #include <boost/python/return_value_policy.hpp>
5 #include <boost/python/manage_new_object.hpp>
6
7 #include <boost/python/register_ptr_to_python.hpp>
8 using namespace boost::python;
9
10 #include "alg/annotations.hpp"
11 #include "stl_container_adapter.hpp"
12
13 #include <stdexcept>
14
15 typedef std::pair<std::string const, std::string> pair_string;
16
17 struct pair_string_to_tuple 
18 {
19   static PyObject * convert(pair_string const &p) {
20     PyObject *key = PyString_FromString(p.first.c_str());
21     PyObject *value = PyString_FromString(p.second.c_str());
22     PyObject *tuple = PyTuple_New(2);
23     if (key == 0 or value == 0 or tuple == 0) 
24       throw std::runtime_error("Allocation Error");
25
26     PyTuple_SetItem(tuple, 0, key);
27     PyTuple_SetItem(tuple, 1, value);
28     return tuple;
29   }
30 };
31
32 void export_annotations()
33 {
34   to_python_converter<pair_string, pair_string_to_tuple>();
35
36   class_<Annotations>("annotations", init<std::string>())
37     .add_property("name", &Annotations::name, &Annotations::setName)
38     .def("__contains__", &map_item<Annotations>::in)
39     .def("__delitem__", &map_item<Annotations>::del)
40     .def("__getitem__", &map_item<Annotations>::get,
41          return_value_policy<copy_non_const_reference>())
42     .def("__setitem__", &map_item<Annotations>::set)
43     .def("__iter__", iterator<Annotations>())
44     .def("__len__", &Annotations::size)
45     .def("keys", &map_item<Annotations>::keys)
46     .def("values", &map_item<Annotations>::values)
47     .def("items", &map_item<Annotations>::items)
48
49     ;
50
51   //register_ptr_to_python< AnnotationsRef >();
52 }