Michele De Stefano's C++ Utilities
obj_usage.i
1 // obj_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 obj_usage_wrap.cpp obj_usage.i
11  *
12  * 2. python setup.py build
13  */
14 
15 /**
16  * \example obj_usage.i
17  *
18  * A simple SWIG interface for a Python extension module that shows the
19  * mds_utils::python::Obj usage.
20  *
21  * \remarks Here I've used SWIG for convenience only. The
22  * mds_utils::python::Obj class does not impose you
23  * this choice.
24  */
25 
26 %module obj_usage
27 
28 // Include the following interface files for having the proper typemaps
29 %include "std_string.i"
30 %include "mds_utils/python/common.i"
31 %include "mds_utils/python/obj.i"
32 
33 %header %{
34 #include <mds_utils/python/obj.hpp>
35 #include <mds_utils/python/conversion.hpp>
36 #include <iostream>
37 
38 namespace mdspy = mds_utils::python;
39 %}
40 
41 %feature("autodoc","3");
42 
43 %inline %{
44 
45 // Tests attribute retrieval, when the attribute is a double
46 void print_attr(mds_utils::python::Obj o,const std::string& name) {
47  using namespace std;
48 
49  o.incref();
50 
51  if (!o.has_attr(name)) {
52  cout << "The object has not the \"" << name << "\" attribute." << endl;
53  return;
54  }
55 
56  cout << "Attribute value: " << mdspy::get<double>(o.attr(name)) << endl;
57 
58  o.decref();
59 }
60 
61 
62 // Tests the set attribute
63 void set_attr(mds_utils::python::Obj o,const std::string& name,double val) {
64  o.attr(name) = val;
65 }
66 
67 
68 // Tests the transfer method
69 PyObject* dup_obj(mds_utils::python::Obj o) {
70 
71  o.incref();
72 
73  PyObject *pret(o.transfer());
74 
75  return pret;
76 }
77 
78 
79 // Tests the operator () for callable objects
80 mds_utils::python::Obj test_call(mds_utils::python::Obj o) {
81 
82  mdspy::Obj
83  out(o());
84 
85  return out;
86 }
87 
88 // Tests the operator () on a callable attribute
89 mds_utils::python::Obj test_call_attr(mds_utils::python::Obj o,const std::string& name) {
90 
91  mdspy::Obj
92  out(o.attr(name)());
93 
94  return out;
95 }
96 
97 
98 // Tests calling an object with positional arguments
99 mds_utils::python::Obj test_call_args(mds_utils::python::Obj o,mds_utils::python::Obj args) {
100 
101  mdspy::Obj
102  out(o(args));
103 
104  return out;
105 }
106 
107 
108 // Tests calling an object with positional arguments and keyword arguments
109 mds_utils::python::Obj test_call_args_kw(mds_utils::python::Obj o,
110  mds_utils::python::Obj args,
111  mds_utils::python::Obj kw) {
112 
113  mdspy::Obj
114  out(o(args,kw));
115 
116  return out;
117 }
118 
119 %}