Michele De Stefano's C++ Utilities
tuple_usage.i
1 // tuple_usage.i
2 //
3 // Copyright (c) 2014 - Michele De Stefano (micdestefano@users.sourceforge.net)
4 //
5 // Distributed under the MIT License (See accompanying file LICENSE)
6 
7 /*
8  * Instructions for generating and building the extension:
9  *
10  * 1. swig -c++ -Wall -python -I../../../include -o tuple_usage_wrap.cpp tuple_usage.i
11  *
12  * 2. python setup.py build
13  */
14 
15 /**
16  * \example tuple_usage.i
17  *
18  * A simple SWIG interface for a Python extension module that shows the
19  * mds_utils::python::Tuple usage.
20  *
21  * \remarks Here I've used SWIG for convenience only. The
22  * mds_utils::python::Tuple class does not impose you
23  * this choice.
24  */
25 
26 %module tuple_usage
27 
28 // Include the following interface files for having the proper typemaps
29 %include "mds_utils/python/common.i"
30 %include "mds_utils/python/tuple.i"
31 
32 
33 %header %{
34 #include <mds_utils/python/conversion.hpp>
35 #include <mds_utils/python/tuple.hpp>
36 #include <mds_utils/python/sequence_iterator.hpp>
37 #include <boost/fusion/container/vector.hpp>
38 #include <iostream>
39 
40 namespace mdspy = mds_utils::python;
41 %}
42 
43 
44 %inline %{
45 
46 // Tests the call to Tuple::set(mdspy::Obj)
47 PyObject* create_tuple(mds_utils::python::Obj o) {
48 
49  using namespace std;
50 
51  mdspy::Tuple t;
52 
53  t.set(o);
54 
55  cout << "Built tuple length: " << t.len() << endl;
56 
57  PyObject *pret(t.transfer());
58 
59  return pret;
60 }
61 
62 
63 // Tests the call to Tuple::set(const seq_T&)
64 PyObject* create_from_fusion() {
65 
66  namespace fus = boost::fusion;
67 
68  mdspy::Tuple t;
69 
70  fus::vector<int,double,std::string>
71  v(1,2.2,"aaa");
72 
73  t.set(v);
74 
75  return t.transfer();
76 }
77 
78 
79 // Tests the Tuple::set(FwIt,FwIt) method
80 PyObject* create_from_seq(mds_utils::python::Obj o) {
81 
82  mdspy::PySequenceIterator<mdspy::Obj>
83  b(o),
84  e(o,true);
85 
86  mdspy::Tuple t;
87 
88  t.set(b,e);
89 
90  return t.transfer();
91 }
92 
93 
94 // Like the previous one, but returning directly a mdspy::Tuple
95 // This tests the output typemap
96 mds_utils::python::Tuple create_from_seq2(mds_utils::python::Obj o) {
97 
98  mdspy::PySequenceIterator<mdspy::Obj>
99  b(o),
100  e(o,true);
101 
102  mdspy::Tuple t;
103 
104  t.set(b,e);
105 
106  return t;
107 }
108 
109 // Test for element access with operator []
110 mds_utils::python::Obj access_element(mds_utils::python::Obj o,long i) {
111  mdspy::Tuple t(o);
112  return t[i];
113 }
114 
115 
116 // This shows that the assignment to an element of the tuple fails
117 void set_element(mds_utils::python::Obj o,long i,mds_utils::python::Obj v) {
118  mdspy::Tuple t(o);
119  t[i] = v;
120 }
121 
122 
123 %}