tutorial.qbk 60 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951
  1. [article Boost.Python Tutorial
  2. [quickbook 1.6]
  3. [authors [de Guzman, Joel], [Abrahams, David]]
  4. [copyright 2002 2003 2004 2005 Joel de Guzman, David Abrahams]
  5. [category inter-language support]
  6. [id tutorial]
  7. [purpose
  8. Reflects C++ classes and functions into Python
  9. ]
  10. [license
  11. Distributed under the Boost Software License, Version 1.0.
  12. (See accompanying file LICENSE_1_0.txt or copy at
  13. [@http://www.boost.org/LICENSE_1_0.txt]
  14. ]
  15. ]
  16. [/ QuickBook Document version 0.9 ]
  17. [def __note__ [$../images/note.png]]
  18. [def __alert__ [$../images/alert.png]]
  19. [def __tip__ [$../images/tip.png]]
  20. [def :-) [$../images/smiley.png]]
  21. [def __jam__ [$../images/jam.png]]
  22. [section QuickStart]
  23. The Boost Python Library is a framework for interfacing Python and
  24. C++. It allows you to quickly and seamlessly expose C++ classes
  25. functions and objects to Python, and vice-versa, using no special
  26. tools -- just your C++ compiler. It is designed to wrap C++ interfaces
  27. non-intrusively, so that you should not have to change the C++ code at
  28. all in order to wrap it, making Boost.Python ideal for exposing
  29. 3rd-party libraries to Python. The library's use of advanced
  30. metaprogramming techniques simplifies its syntax for users, so that
  31. wrapping code takes on the look of a kind of declarative interface
  32. definition language (IDL).
  33. [h2 Hello World]
  34. Following C/C++ tradition, let's start with the "hello, world". A C++
  35. Function:
  36. char const* greet()
  37. {
  38. return "hello, world";
  39. }
  40. can be exposed to Python by writing a Boost.Python wrapper:
  41. #include <boost/python.hpp>
  42. BOOST_PYTHON_MODULE(hello_ext)
  43. {
  44. using namespace boost::python;
  45. def("greet", greet);
  46. }
  47. That's it. We're done. We can now build this as a shared library. The
  48. resulting DLL is now visible to Python. Here's a sample Python session:
  49. [python]
  50. >>> import hello_ext
  51. >>> print hello_ext.greet()
  52. hello, world
  53. [c++]
  54. [:['[*Next stop... Building your Hello World module from start to finish...]]]
  55. [endsect]
  56. [section:hello Building Hello World]
  57. [h2 From Start To Finish]
  58. Now the first thing you'd want to do is to build the Hello World module and
  59. try it for yourself in Python. In this section, we will outline the steps
  60. necessary to achieve that. We will use the build tool that comes bundled
  61. with every boost distribution: [*bjam].
  62. [note [*Building without bjam]
  63. Besides bjam, there are of course other ways to get your module built.
  64. What's written here should not be taken as "the one and only way".
  65. There are of course other build tools apart from [^bjam].
  66. Take note however that the preferred build tool for Boost.Python is bjam.
  67. There are so many ways to set up the build incorrectly. Experience shows
  68. that 90% of the "I can't build Boost.Python" problems come from people
  69. who had to use a different tool.
  70. ]
  71. We will skip over the details. Our objective will be to simply create
  72. the hello world module and run it in Python. For a complete reference to
  73. building Boost.Python, check out: [@../building.html
  74. building.html]. After this brief ['bjam] tutorial, we should have built
  75. the DLLs and run a python program using the extension.
  76. The tutorial example can be found in the directory:
  77. [^libs/python/example/tutorial]. There, you can find:
  78. * hello.cpp
  79. * hello.py
  80. * Jamroot
  81. The [^hello.cpp] file is our C++ hello world example. The [^Jamroot] is
  82. a minimalist ['bjam] script that builds the DLLs for us. Finally,
  83. [^hello.py] is our Python program that uses the extension in
  84. [^hello.cpp].
  85. Before anything else, you should have the bjam executable in your boost
  86. directory or somewhere in your path such that [^bjam] can be executed in
  87. the command line. Pre-built Boost.Jam executables are available for most
  88. platforms. The complete list of Bjam executables can be found
  89. [@http://sourceforge.net/project/showfiles.php?group_id=7586 here].
  90. [h2 Let's Jam!]
  91. __jam__
  92. [@../../../../example/tutorial/Jamroot Here] is our minimalist Jamroot
  93. file. Simply copy the file and tweak [^use-project boost] to where your
  94. boost root directory is and you're OK.
  95. The comments contained in the Jamroot file above should be sufficient
  96. to get you going.
  97. [h2 Running bjam]
  98. ['bjam] is run using your operating system's command line interpreter.
  99. [:Start it up.]
  100. A file called user-config.jam in your home directory is used to
  101. configure your tools. In Windows, your home directory can be found by
  102. typing:
  103. [pre
  104. ECHO %HOMEDRIVE%%HOMEPATH%
  105. ]
  106. into a command prompt window. Your file should at least have the rules
  107. for your compiler and your python installation. A specific example of
  108. this on Windows would be:
  109. [pre
  110. # MSVC configuration
  111. using msvc : 8.0 ;
  112. # Python configuration
  113. using python : 2.4 : C:/dev/tools/Python/ ;
  114. ]
  115. The first rule tells Bjam to use the MSVC 8.0 compiler and associated
  116. tools. The second rule provides information on Python, its version and
  117. where it is located. The above assumes that the Python installation is
  118. in [^C:/dev/tools\/Python/]. If you have one fairly "standard" python
  119. installation for your platform, you might not need to do this.
  120. Now we are ready... Be sure to [^cd] to [^libs/python/example/tutorial]
  121. where the tutorial [^"hello.cpp"] and the [^"Jamroot"] is situated.
  122. Finally:
  123. bjam
  124. It should be building now:
  125. [pre
  126. cd C:\dev\boost\libs\python\example\tutorial
  127. bjam
  128. ...patience...
  129. ...found 1101 targets...
  130. ...updating 35 targets...
  131. ]
  132. And so on... Finally:
  133. [pre
  134. Creating library /path-to-boost_python.dll/
  135. Creating library /path-to-'''hello_ext'''.exp/
  136. '''**passed**''' ... hello.test
  137. ...updated 35 targets...
  138. ]
  139. Or something similar. If all is well, you should now have built the DLLs and
  140. run the Python program.
  141. [:[*There you go... Have fun!]]
  142. [endsect]
  143. [section:exposing Exposing Classes]
  144. Now let's expose a C++ class to Python.
  145. Consider a C++ class/struct that we want to expose to Python:
  146. struct World
  147. {
  148. void set(std::string msg) { this->msg = msg; }
  149. std::string greet() { return msg; }
  150. std::string msg;
  151. };
  152. We can expose this to Python by writing a corresponding Boost.Python
  153. C++ Wrapper:
  154. #include <boost/python.hpp>
  155. using namespace boost::python;
  156. BOOST_PYTHON_MODULE(hello)
  157. {
  158. class_<World>("World")
  159. .def("greet", &World::greet)
  160. .def("set", &World::set)
  161. ;
  162. }
  163. Here, we wrote a C++ class wrapper that exposes the member functions
  164. [^greet] and [^set]. Now, after building our module as a shared library, we
  165. may use our class [^World] in Python. Here's a sample Python session:
  166. [python]
  167. >>> import hello
  168. >>> planet = hello.World()
  169. >>> planet.set('howdy')
  170. >>> planet.greet()
  171. 'howdy'
  172. [section Constructors]
  173. Our previous example didn't have any explicit constructors.
  174. Since [^World] is declared as a plain struct, it has an implicit default
  175. constructor. Boost.Python exposes the default constructor by default,
  176. which is why we were able to write
  177. >>> planet = hello.World()
  178. We may wish to wrap a class with a non-default constructor. Let us
  179. build on our previous example:
  180. [c++]
  181. struct World
  182. {
  183. World(std::string msg): msg(msg) {} // added constructor
  184. void set(std::string msg) { this->msg = msg; }
  185. std::string greet() { return msg; }
  186. std::string msg;
  187. };
  188. This time [^World] has no default constructor; our previous
  189. wrapping code would fail to compile when the library tried to expose
  190. it. We have to tell [^class_<World>] about the constructor we want to
  191. expose instead.
  192. #include <boost/python.hpp>
  193. using namespace boost::python;
  194. BOOST_PYTHON_MODULE(hello)
  195. {
  196. class_<World>("World", init<std::string>())
  197. .def("greet", &World::greet)
  198. .def("set", &World::set)
  199. ;
  200. }
  201. [^init<std::string>()] exposes the constructor taking in a
  202. [^std::string] (in Python, constructors are spelled
  203. "[^"__init__"]").
  204. We can expose additional constructors by passing more [^init<...>]s to
  205. the [^def()] member function. Say for example we have another World
  206. constructor taking in two doubles:
  207. class_<World>("World", init<std::string>())
  208. .def(init<double, double>())
  209. .def("greet", &World::greet)
  210. .def("set", &World::set)
  211. ;
  212. On the other hand, if we do not wish to expose any constructors at
  213. all, we may use [^no_init] instead:
  214. class_<Abstract>("Abstract", no_init)
  215. This actually adds an [^__init__] method which always raises a
  216. Python RuntimeError exception.
  217. [endsect]
  218. [section Class Data Members]
  219. Data members may also be exposed to Python so that they can be
  220. accessed as attributes of the corresponding Python class. Each data
  221. member that we wish to be exposed may be regarded as [*read-only] or
  222. [*read-write]. Consider this class [^Var]:
  223. struct Var
  224. {
  225. Var(std::string name) : name(name), value() {}
  226. std::string const name;
  227. float value;
  228. };
  229. Our C++ [^Var] class and its data members can be exposed to Python:
  230. class_<Var>("Var", init<std::string>())
  231. .def_readonly("name", &Var::name)
  232. .def_readwrite("value", &Var::value);
  233. Then, in Python, assuming we have placed our Var class inside the namespace
  234. hello as we did before:
  235. [python]
  236. >>> x = hello.Var('pi')
  237. >>> x.value = 3.14
  238. >>> print x.name, 'is around', x.value
  239. pi is around 3.14
  240. Note that [^name] is exposed as [*read-only] while [^value] is exposed
  241. as [*read-write].
  242. >>> x.name = 'e' # can't change name
  243. Traceback (most recent call last):
  244. File "<stdin>", line 1, in ?
  245. AttributeError: can't set attribute
  246. [endsect]
  247. [section Class Properties]
  248. In C++, classes with public data members are usually frowned
  249. upon. Well designed classes that take advantage of encapsulation hide
  250. the class' data members. The only way to access the class' data is
  251. through access (getter/setter) functions. Access functions expose class
  252. properties. Here's an example:
  253. [c++]
  254. struct Num
  255. {
  256. Num();
  257. float get() const;
  258. void set(float value);
  259. ...
  260. };
  261. However, in Python attribute access is fine; it doesn't neccessarily break
  262. encapsulation to let users handle attributes directly, because the
  263. attributes can just be a different syntax for a method call. Wrapping our
  264. [^Num] class using Boost.Python:
  265. class_<Num>("Num")
  266. .add_property("rovalue", &Num::get)
  267. .add_property("value", &Num::get, &Num::set);
  268. And at last, in Python:
  269. [python]
  270. >>> x = Num()
  271. >>> x.value = 3.14
  272. >>> x.value, x.rovalue
  273. (3.14, 3.14)
  274. >>> x.rovalue = 2.17 # error!
  275. Take note that the class property [^rovalue] is exposed as [*read-only]
  276. since the [^rovalue] setter member function is not passed in:
  277. [c++]
  278. .add_property("rovalue", &Num::get)
  279. [endsect]
  280. [section Inheritance]
  281. In the previous examples, we dealt with classes that are not polymorphic.
  282. This is not often the case. Much of the time, we will be wrapping
  283. polymorphic classes and class hierarchies related by inheritance. We will
  284. often have to write Boost.Python wrappers for classes that are derived from
  285. abstract base classes.
  286. Consider this trivial inheritance structure:
  287. struct Base { virtual ~Base(); };
  288. struct Derived : Base {};
  289. And a set of C++ functions operating on [^Base] and [^Derived] object
  290. instances:
  291. void b(Base*);
  292. void d(Derived*);
  293. Base* factory() { return new Derived; }
  294. We've seen how we can wrap the base class [^Base]:
  295. class_<Base>("Base")
  296. /*...*/
  297. ;
  298. Now we can inform Boost.Python of the inheritance relationship between
  299. [^Derived] and its base class [^Base]. Thus:
  300. class_<Derived, bases<Base> >("Derived")
  301. /*...*/
  302. ;
  303. Doing so, we get some things for free:
  304. # Derived automatically inherits all of Base's Python methods
  305. (wrapped C++ member functions)
  306. # [*If] Base is polymorphic, [^Derived] objects which have been passed to
  307. Python via a pointer or reference to [^Base] can be passed where a pointer
  308. or reference to [^Derived] is expected.
  309. Now, we will expose the C++ free functions [^b] and [^d] and [^factory]:
  310. def("b", b);
  311. def("d", d);
  312. def("factory", factory);
  313. Note that free function [^factory] is being used to generate new
  314. instances of class [^Derived]. In such cases, we use
  315. [^return_value_policy<manage_new_object>] to instruct Python to adopt
  316. the pointer to [^Base] and hold the instance in a new Python [^Base]
  317. object until the the Python object is destroyed. We will see more of
  318. Boost.Python [link tutorial.functions.call_policies call policies] later.
  319. // Tell Python to take ownership of factory's result
  320. def("factory", factory,
  321. return_value_policy<manage_new_object>());
  322. [endsect]
  323. [section Class Virtual Functions]
  324. In this section, we will learn how to make functions behave polymorphically
  325. through virtual functions. Continuing our example, let us add a virtual function
  326. to our [^Base] class:
  327. struct Base
  328. {
  329. virtual ~Base() {}
  330. virtual int f() = 0;
  331. };
  332. One of the goals of Boost.Python is to be minimally intrusive on an existing C++
  333. design. In principle, it should be possible to expose the interface for a 3rd
  334. party library without changing it. It is not ideal to add anything to our class
  335. `Base`. Yet, when you have a virtual function that's going to be overridden in
  336. Python and called polymorphically *from C++*, we'll need to add some
  337. scaffoldings to make things work properly. What we'll do is write a class
  338. wrapper that derives from `Base` that will unintrusively hook into the virtual
  339. functions so that a Python override may be called:
  340. struct BaseWrap : Base, wrapper<Base>
  341. {
  342. int f()
  343. {
  344. return this->get_override("f")();
  345. }
  346. };
  347. Notice too that in addition to inheriting from `Base`, we also multiply-
  348. inherited `wrapper<Base>` (See [@../reference/high_level_components/boost_python_wrapper_hpp.html#high_level_components.boost_python_wrapper_hpp.class_template_wrapper Wrapper]). The
  349. `wrapper` template makes the job of wrapping classes that are meant to
  350. overridden in Python, easier.
  351. [blurb __alert__ [*MSVC6/7 Workaround]
  352. If you are using Microsoft Visual C++ 6 or 7, you have to write `f` as:
  353. `return call<int>(this->get_override("f").ptr());`.]
  354. BaseWrap's overridden virtual member function `f` in effect calls the
  355. corresponding method of the Python object through `get_override`.
  356. Finally, exposing `Base`:
  357. class_<BaseWrap, boost::noncopyable>("Base")
  358. .def("f", pure_virtual(&Base::f))
  359. ;
  360. `pure_virtual` signals Boost.Python that the function `f` is a pure virtual
  361. function.
  362. [note [*member function and methods]
  363. Python, like many object oriented languages uses the term [*methods].
  364. Methods correspond roughly to C++'s [*member functions]]
  365. [endsect]
  366. [section Virtual Functions with Default Implementations]
  367. We've seen in the previous section how classes with pure virtual functions are
  368. wrapped using Boost.Python's [@../reference/high_level_components/boost_python_wrapper_hpp.html#high_level_components.boost_python_wrapper_hpp.class_template_wrapper class wrapper]
  369. facilities. If we wish to wrap [*non]-pure-virtual functions instead, the
  370. mechanism is a bit different.
  371. Recall that in the [link tutorial.exposing.class_virtual_functions previous section], we
  372. wrapped a class with a pure virtual function that we then implemented in C++, or
  373. Python classes derived from it. Our base class:
  374. struct Base
  375. {
  376. virtual int f() = 0;
  377. };
  378. had a pure virtual function [^f]. If, however, its member function [^f] was
  379. not declared as pure virtual:
  380. struct Base
  381. {
  382. virtual ~Base() {}
  383. virtual int f() { return 0; }
  384. };
  385. We wrap it this way:
  386. struct BaseWrap : Base, wrapper<Base>
  387. {
  388. int f()
  389. {
  390. if (override f = this->get_override("f"))
  391. return f(); // *note*
  392. return Base::f();
  393. }
  394. int default_f() { return this->Base::f(); }
  395. };
  396. Notice how we implemented `BaseWrap::f`. Now, we have to check if there is an
  397. override for `f`. If none, then we call `Base::f()`.
  398. [blurb __alert__ [*MSVC6/7 Workaround]
  399. If you are using Microsoft Visual C++ 6 or 7, you have to rewrite the line
  400. with the `*note*` as:
  401. `return call<char const*>(f.ptr());`.]
  402. Finally, exposing:
  403. class_<BaseWrap, boost::noncopyable>("Base")
  404. .def("f", &Base::f, &BaseWrap::default_f)
  405. ;
  406. Take note that we expose both `&Base::f` and `&BaseWrap::default_f`.
  407. Boost.Python needs to keep track of 1) the dispatch function [^f] and 2) the
  408. forwarding function to its default implementation [^default_f]. There's a
  409. special [^def] function for this purpose.
  410. In Python, the results would be as expected:
  411. [python]
  412. >>> base = Base()
  413. >>> class Derived(Base):
  414. ... def f(self):
  415. ... return 42
  416. ...
  417. >>> derived = Derived()
  418. Calling [^base.f()]:
  419. >>> base.f()
  420. 0
  421. Calling [^derived.f()]:
  422. >>> derived.f()
  423. 42
  424. [endsect]
  425. [section Class Operators/Special Functions]
  426. [h2 Python Operators]
  427. C is well known for the abundance of operators. C++ extends this to the
  428. extremes by allowing operator overloading. Boost.Python takes advantage of
  429. this and makes it easy to wrap C++ operator-powered classes.
  430. Consider a file position class [^FilePos] and a set of operators that take
  431. on FilePos instances:
  432. [c++]
  433. class FilePos { /*...*/ };
  434. FilePos operator+(FilePos, int);
  435. FilePos operator+(int, FilePos);
  436. int operator-(FilePos, FilePos);
  437. FilePos operator-(FilePos, int);
  438. FilePos& operator+=(FilePos&, int);
  439. FilePos& operator-=(FilePos&, int);
  440. bool operator<(FilePos, FilePos);
  441. The class and the various operators can be mapped to Python rather easily
  442. and intuitively:
  443. class_<FilePos>("FilePos")
  444. .def(self + int()) // __add__
  445. .def(int() + self) // __radd__
  446. .def(self - self) // __sub__
  447. .def(self - int()) // __sub__
  448. .def(self += int()) // __iadd__
  449. .def(self -= other<int>())
  450. .def(self < self); // __lt__
  451. The code snippet above is very clear and needs almost no explanation at
  452. all. It is virtually the same as the operators' signatures. Just take
  453. note that [^self] refers to FilePos object. Also, not every class [^T] that
  454. you might need to interact with in an operator expression is (cheaply)
  455. default-constructible. You can use [^other<T>()] in place of an actual
  456. [^T] instance when writing "self expressions".
  457. [h2 Special Methods]
  458. Python has a few more ['Special Methods]. Boost.Python supports all of the
  459. standard special method names supported by real Python class instances. A
  460. similar set of intuitive interfaces can also be used to wrap C++ functions
  461. that correspond to these Python ['special functions]. Example:
  462. class Rational
  463. { public: operator double() const; };
  464. Rational pow(Rational, Rational);
  465. Rational abs(Rational);
  466. ostream& operator<<(ostream&,Rational);
  467. class_<Rational>("Rational")
  468. .def(float_(self)) // __float__
  469. .def(pow(self, other<Rational>)) // __pow__
  470. .def(abs(self)) // __abs__
  471. .def(str(self)) // __str__
  472. ;
  473. Need we say more?
  474. [note What is the business of `operator<<`?
  475. Well, the method `str` requires the `operator<<` to do its work (i.e.
  476. `operator<<` is used by the method defined by `def(str(self))`.]
  477. [endsect]
  478. [endsect] [/ Exposing Classes ]
  479. [section Functions]
  480. In this chapter, we'll look at Boost.Python powered functions in closer
  481. detail. We will see some facilities to make exposing C++ functions to
  482. Python safe from potential pifalls such as dangling pointers and
  483. references. We will also see facilities that will make it even easier for
  484. us to expose C++ functions that take advantage of C++ features such as
  485. overloading and default arguments.
  486. [:['Read on...]]
  487. But before you do, you might want to fire up Python 2.2 or later and type
  488. [^>>> import this].
  489. [pre
  490. >>> import this
  491. The Zen of Python, by Tim Peters
  492. Beautiful is better than ugly.
  493. Explicit is better than implicit.
  494. Simple is better than complex.
  495. Complex is better than complicated.
  496. Flat is better than nested.
  497. Sparse is better than dense.
  498. Readability counts.
  499. Special cases aren't special enough to break the rules.
  500. Although practicality beats purity.
  501. Errors should never pass silently.
  502. Unless explicitly silenced.
  503. In the face of ambiguity, refuse the temptation to guess.
  504. There should be one-- and preferably only one --obvious way to do it
  505. Although that way may not be obvious at first unless you're Dutch.
  506. Now is better than never.
  507. Although never is often better than *right* now.
  508. If the implementation is hard to explain, it's a bad idea.
  509. If the implementation is easy to explain, it may be a good idea.
  510. Namespaces are one honking great idea -- let's do more of those!
  511. ]
  512. [section Call Policies]
  513. In C++, we often deal with arguments and return types such as pointers
  514. and references. Such primitive types are rather, ummmm, low level and
  515. they really don't tell us much. At the very least, we don't know the
  516. owner of the pointer or the referenced object. No wonder languages
  517. such as Java and Python never deal with such low level entities. In
  518. C++, it's usually considered a good practice to use smart pointers
  519. which exactly describe ownership semantics. Still, even good C++
  520. interfaces use raw references and pointers sometimes, so Boost.Python
  521. must deal with them. To do this, it may need your help. Consider the
  522. following C++ function:
  523. X& f(Y& y, Z* z);
  524. How should the library wrap this function? A naive approach builds a
  525. Python X object around result reference. This strategy might or might
  526. not work out. Here's an example where it didn't
  527. >>> x = f(y, z) # x refers to some C++ X
  528. >>> del y
  529. >>> x.some_method() # CRASH!
  530. What's the problem?
  531. Well, what if f() was implemented as shown below:
  532. X& f(Y& y, Z* z)
  533. {
  534. y.z = z;
  535. return y.x;
  536. }
  537. The problem is that the lifetime of result X& is tied to the lifetime
  538. of y, because the f() returns a reference to a member of the y
  539. object. This idiom is is not uncommon and perfectly acceptable in the
  540. context of C++. However, Python users should not be able to crash the
  541. system just by using our C++ interface. In this case deleting y will
  542. invalidate the reference to X. We have a dangling reference.
  543. Here's what's happening:
  544. # [^f] is called passing in a reference to [^y] and a pointer to [^z]
  545. # A reference to [^y.x] is returned
  546. # [^y] is deleted. [^x] is a dangling reference
  547. # [^x.some_method()] is called
  548. # [*BOOM!]
  549. We could copy result into a new object:
  550. [python]
  551. >>> f(y, z).set(42) # Result disappears
  552. >>> y.x.get() # No crash, but still bad
  553. 3.14
  554. This is not really our intent of our C++ interface. We've broken our
  555. promise that the Python interface should reflect the C++ interface as
  556. closely as possible.
  557. Our problems do not end there. Suppose Y is implemented as follows:
  558. [c++]
  559. struct Y
  560. {
  561. X x; Z* z;
  562. int z_value() { return z->value(); }
  563. };
  564. Notice that the data member [^z] is held by class Y using a raw
  565. pointer. Now we have a potential dangling pointer problem inside Y:
  566. >>> x = f(y, z) # y refers to z
  567. >>> del z # Kill the z object
  568. >>> y.z_value() # CRASH!
  569. For reference, here's the implementation of [^f] again:
  570. X& f(Y& y, Z* z)
  571. {
  572. y.z = z;
  573. return y.x;
  574. }
  575. Here's what's happening:
  576. # [^f] is called passing in a reference to [^y] and a pointer to [^z]
  577. # A pointer to [^z] is held by [^y]
  578. # A reference to [^y.x] is returned
  579. # [^z] is deleted. [^y.z] is a dangling pointer
  580. # [^y.z_value()] is called
  581. # [^z->value()] is called
  582. # [*BOOM!]
  583. [h2 Call Policies]
  584. Call Policies may be used in situations such as the example detailed above.
  585. In our example, [^return_internal_reference] and [^with_custodian_and_ward]
  586. are our friends:
  587. def("f", f,
  588. return_internal_reference<1,
  589. with_custodian_and_ward<1, 2> >());
  590. What are the [^1] and [^2] parameters, you ask?
  591. return_internal_reference<1
  592. Informs Boost.Python that the first argument, in our case [^Y& y], is the
  593. owner of the returned reference: [^X&]. The "[^1]" simply specifies the
  594. first argument. In short: "return an internal reference [^X&] owned by the
  595. 1st argument [^Y& y]".
  596. with_custodian_and_ward<1, 2>
  597. Informs Boost.Python that the lifetime of the argument indicated by ward
  598. (i.e. the 2nd argument: [^Z* z]) is dependent on the lifetime of the
  599. argument indicated by custodian (i.e. the 1st argument: [^Y& y]).
  600. It is also important to note that we have defined two policies above. Two
  601. or more policies can be composed by chaining. Here's the general syntax:
  602. policy1<args...,
  603. policy2<args...,
  604. policy3<args...> > >
  605. Here is the list of predefined call policies. A complete reference detailing
  606. these can be found [@../reference/function_invocation_and_creation/models_of_callpolicies.html here].
  607. * [*with_custodian_and_ward]: Ties lifetimes of the arguments
  608. * [*with_custodian_and_ward_postcall]: Ties lifetimes of the arguments and results
  609. * [*return_internal_reference]: Ties lifetime of one argument to that of result
  610. * [*return_value_policy<T> with T one of:]
  611. * [*reference_existing_object]: naive (dangerous) approach
  612. * [*copy_const_reference]: Boost.Python v1 approach
  613. * [*copy_non_const_reference]:
  614. * [*manage_new_object]: Adopt a pointer and hold the instance
  615. [blurb :-) [*Remember the Zen, Luke:]
  616. "Explicit is better than implicit"
  617. "In the face of ambiguity, refuse the temptation to guess"
  618. ]
  619. [endsect]
  620. [section Overloading]
  621. The following illustrates a scheme for manually wrapping an overloaded
  622. member functions. Of course, the same technique can be applied to wrapping
  623. overloaded non-member functions.
  624. We have here our C++ class:
  625. struct X
  626. {
  627. bool f(int a)
  628. {
  629. return true;
  630. }
  631. bool f(int a, double b)
  632. {
  633. return true;
  634. }
  635. bool f(int a, double b, char c)
  636. {
  637. return true;
  638. }
  639. int f(int a, int b, int c)
  640. {
  641. return a + b + c;
  642. };
  643. };
  644. Class X has 4 overloaded functions. We will start by introducing some
  645. member function pointer variables:
  646. bool (X::*fx1)(int) = &X::f;
  647. bool (X::*fx2)(int, double) = &X::f;
  648. bool (X::*fx3)(int, double, char)= &X::f;
  649. int (X::*fx4)(int, int, int) = &X::f;
  650. With these in hand, we can proceed to define and wrap this for Python:
  651. .def("f", fx1)
  652. .def("f", fx2)
  653. .def("f", fx3)
  654. .def("f", fx4)
  655. [endsect]
  656. [section Default Arguments]
  657. Boost.Python wraps (member) function pointers. Unfortunately, C++ function
  658. pointers carry no default argument info. Take a function [^f] with default
  659. arguments:
  660. int f(int, double = 3.14, char const* = "hello");
  661. But the type of a pointer to the function [^f] has no information
  662. about its default arguments:
  663. int(*g)(int,double,char const*) = f; // defaults lost!
  664. When we pass this function pointer to the [^def] function, there is no way
  665. to retrieve the default arguments:
  666. def("f", f); // defaults lost!
  667. Because of this, when wrapping C++ code, we had to resort to manual
  668. wrapping as outlined in the [link tutorial.functions.overloading previous section], or
  669. writing thin wrappers:
  670. // write "thin wrappers"
  671. int f1(int x) { return f(x); }
  672. int f2(int x, double y) { return f(x,y); }
  673. /*...*/
  674. // in module init
  675. def("f", f); // all arguments
  676. def("f", f2); // two arguments
  677. def("f", f1); // one argument
  678. When you want to wrap functions (or member functions) that either:
  679. * have default arguments, or
  680. * are overloaded with a common sequence of initial arguments
  681. [h2 BOOST_PYTHON_FUNCTION_OVERLOADS]
  682. Boost.Python now has a way to make it easier. For instance, given a function:
  683. int foo(int a, char b = 1, unsigned c = 2, double d = 3)
  684. {
  685. /*...*/
  686. }
  687. The macro invocation:
  688. BOOST_PYTHON_FUNCTION_OVERLOADS(foo_overloads, foo, 1, 4)
  689. will automatically create the thin wrappers for us. This macro will create
  690. a class [^foo_overloads] that can be passed on to [^def(...)]. The third
  691. and fourth macro argument are the minimum arguments and maximum arguments,
  692. respectively. In our [^foo] function the minimum number of arguments is 1
  693. and the maximum number of arguments is 4. The [^def(...)] function will
  694. automatically add all the foo variants for us:
  695. def("foo", foo, foo_overloads());
  696. [h2 BOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS]
  697. Objects here, objects there, objects here there everywhere. More frequently
  698. than anything else, we need to expose member functions of our classes to
  699. Python. Then again, we have the same inconveniences as before when default
  700. arguments or overloads with a common sequence of initial arguments come
  701. into play. Another macro is provided to make this a breeze.
  702. Like [^BOOST_PYTHON_FUNCTION_OVERLOADS],
  703. [^BOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS] may be used to automatically create
  704. the thin wrappers for wrapping member functions. Let's have an example:
  705. struct george
  706. {
  707. void
  708. wack_em(int a, int b = 0, char c = 'x')
  709. {
  710. /*...*/
  711. }
  712. };
  713. The macro invocation:
  714. BOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS(george_overloads, wack_em, 1, 3)
  715. will generate a set of thin wrappers for george's [^wack_em] member function
  716. accepting a minimum of 1 and a maximum of 3 arguments (i.e. the third and
  717. fourth macro argument). The thin wrappers are all enclosed in a class named
  718. [^george_overloads] that can then be used as an argument to [^def(...)]:
  719. .def("wack_em", &george::wack_em, george_overloads());
  720. See the [@../reference/function_invocation_and_creation/boost_python_overloads_hpp.html#function_invocation_and_creation.boost_python_overloads_hpp.macros overloads reference]
  721. for details.
  722. [h2 init and optional]
  723. A similar facility is provided for class constructors, again, with
  724. default arguments or a sequence of overloads. Remember [^init<...>]? For example,
  725. given a class X with a constructor:
  726. struct X
  727. {
  728. X(int a, char b = 'D', std::string c = "constructor", double d = 0.0);
  729. /*...*/
  730. }
  731. You can easily add this constructor to Boost.Python in one shot:
  732. .def(init<int, optional<char, std::string, double> >())
  733. Notice the use of [^init<...>] and [^optional<...>] to signify the default
  734. (optional arguments).
  735. [endsect]
  736. [section Auto-Overloading]
  737. It was mentioned in passing in the previous section that
  738. [^BOOST_PYTHON_FUNCTION_OVERLOADS] and [^BOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS]
  739. can also be used for overloaded functions and member functions with a
  740. common sequence of initial arguments. Here is an example:
  741. void foo()
  742. {
  743. /*...*/
  744. }
  745. void foo(bool a)
  746. {
  747. /*...*/
  748. }
  749. void foo(bool a, int b)
  750. {
  751. /*...*/
  752. }
  753. void foo(bool a, int b, char c)
  754. {
  755. /*...*/
  756. }
  757. Like in the previous section, we can generate thin wrappers for these
  758. overloaded functions in one-shot:
  759. BOOST_PYTHON_FUNCTION_OVERLOADS(foo_overloads, foo, 0, 3)
  760. Then...
  761. .def("foo", (void(*)(bool, int, char))0, foo_overloads());
  762. Notice though that we have a situation now where we have a minimum of zero
  763. (0) arguments and a maximum of 3 arguments.
  764. [h2 Manual Wrapping]
  765. It is important to emphasize however that [*the overloaded functions must
  766. have a common sequence of initial arguments]. Otherwise, our scheme above
  767. will not work. If this is not the case, we have to wrap our functions
  768. [link tutorial.functions.overloading manually].
  769. Actually, we can mix and match manual wrapping of overloaded functions and
  770. automatic wrapping through [^BOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS] and
  771. its sister, [^BOOST_PYTHON_FUNCTION_OVERLOADS]. Following up on our example
  772. presented in the section [link tutorial.functions.overloading on overloading], since the
  773. first 4 overload functins have a common sequence of initial arguments, we
  774. can use [^BOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS] to automatically wrap the
  775. first three of the [^def]s and manually wrap just the last. Here's
  776. how we'll do this:
  777. BOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS(xf_overloads, f, 1, 4)
  778. Create a member function pointers as above for both X::f overloads:
  779. bool (X::*fx1)(int, double, char) = &X::f;
  780. int (X::*fx2)(int, int, int) = &X::f;
  781. Then...
  782. .def("f", fx1, xf_overloads());
  783. .def("f", fx2)
  784. [endsect]
  785. [endsect] [/ Functions ]
  786. [section:object Object Interface]
  787. Python is dynamically typed, unlike C++ which is statically typed. Python
  788. variables may hold an integer, a float, list, dict, tuple, str, long etc.,
  789. among other things. In the viewpoint of Boost.Python and C++, these
  790. Pythonic variables are just instances of class [^object]. We will see in
  791. this chapter how to deal with Python objects.
  792. As mentioned, one of the goals of Boost.Python is to provide a
  793. bidirectional mapping between C++ and Python while maintaining the Python
  794. feel. Boost.Python C++ [^object]s are as close as possible to Python. This
  795. should minimize the learning curve significantly.
  796. [$../images/python.png]
  797. [section Basic Interface]
  798. Class [^object] wraps [^PyObject*]. All the intricacies of dealing with
  799. [^PyObject]s such as managing reference counting are handled by the
  800. [^object] class. C++ object interoperability is seamless. Boost.Python C++
  801. [^object]s can in fact be explicitly constructed from any C++ object.
  802. To illustrate, this Python code snippet:
  803. [python]
  804. def f(x, y):
  805. if (y == 'foo'):
  806. x[3:7] = 'bar'
  807. else:
  808. x.items += y(3, x)
  809. return x
  810. def getfunc():
  811. return f;
  812. Can be rewritten in C++ using Boost.Python facilities this way:
  813. [c++]
  814. object f(object x, object y) {
  815. if (y == "foo")
  816. x.slice(3,7) = "bar";
  817. else
  818. x.attr("items") += y(3, x);
  819. return x;
  820. }
  821. object getfunc() {
  822. return object(f);
  823. }
  824. Apart from cosmetic differences due to the fact that we are writing the
  825. code in C++, the look and feel should be immediately apparent to the Python
  826. coder.
  827. [endsect]
  828. [section Derived Object types]
  829. Boost.Python comes with a set of derived [^object] types corresponding to
  830. that of Python's:
  831. * list
  832. * dict
  833. * tuple
  834. * str
  835. * long_
  836. * enum
  837. These derived [^object] types act like real Python types. For instance:
  838. str(1) ==> "1"
  839. Wherever appropriate, a particular derived [^object] has corresponding
  840. Python type's methods. For instance, [^dict] has a [^keys()] method:
  841. d.keys()
  842. [^make_tuple] is provided for declaring ['tuple literals]. Example:
  843. make_tuple(123, 'D', "Hello, World", 0.0);
  844. In C++, when Boost.Python [^object]s are used as arguments to functions,
  845. subtype matching is required. For example, when a function [^f], as
  846. declared below, is wrapped, it will only accept instances of Python's
  847. [^str] type and subtypes.
  848. void f(str name)
  849. {
  850. object n2 = name.attr("upper")(); // NAME = name.upper()
  851. str NAME = name.upper(); // better
  852. object msg = "%s is bigger than %s" % make_tuple(NAME,name);
  853. }
  854. In finer detail:
  855. str NAME = name.upper();
  856. Illustrates that we provide versions of the str type's methods as C++
  857. member functions.
  858. object msg = "%s is bigger than %s" % make_tuple(NAME,name);
  859. Demonstrates that you can write the C++ equivalent of [^"format" % x,y,z]
  860. in Python, which is useful since there's no easy way to do that in std C++.
  861. [blurb
  862. __alert__ [*Beware] the common pitfall of forgetting that the constructors
  863. of most of Python's mutable types make copies, just as in Python.
  864. ]
  865. Python:
  866. [python]
  867. >>> d = dict(x.__dict__) # copies x.__dict__
  868. >>> d['whatever'] = 3 # modifies the copy
  869. C++:
  870. [c++]
  871. dict d(x.attr("__dict__")); // copies x.__dict__
  872. d['whatever'] = 3; // modifies the copy
  873. [h2 class_<T> as objects]
  874. Due to the dynamic nature of Boost.Python objects, any [^class_<T>] may
  875. also be one of these types! The following code snippet wraps the class
  876. (type) object.
  877. We can use this to create wrapped instances. Example:
  878. object vec345 = (
  879. class_<Vec2>("Vec2", init<double, double>())
  880. .def_readonly("length", &Point::length)
  881. .def_readonly("angle", &Point::angle)
  882. )(3.0, 4.0);
  883. assert(vec345.attr("length") == 5.0);
  884. [endsect]
  885. [section Extracting C++ objects]
  886. At some point, we will need to get C++ values out of object instances. This
  887. can be achieved with the [^extract<T>] function. Consider the following:
  888. double x = o.attr("length"); // compile error
  889. In the code above, we got a compiler error because Boost.Python
  890. [^object] can't be implicitly converted to [^double]s. Instead, what
  891. we wanted to do above can be achieved by writing:
  892. double l = extract<double>(o.attr("length"));
  893. Vec2& v = extract<Vec2&>(o);
  894. assert(l == v.length());
  895. The first line attempts to extract the "length" attribute of the Boost.Python
  896. [^object]. The second line attempts to ['extract] the [^Vec2] object from held
  897. by the Boost.Python [^object].
  898. Take note that we said "attempt to" above. What if the Boost.Python [^object]
  899. does not really hold a [^Vec2] type? This is certainly a possibility considering
  900. the dynamic nature of Python [^object]s. To be on the safe side, if the C++ type
  901. can't be extracted, an appropriate exception is thrown. To avoid an exception,
  902. we need to test for extractibility:
  903. extract<Vec2&> x(o);
  904. if (x.check()) {
  905. Vec2& v = x(); ...
  906. __tip__ The astute reader might have noticed that the [^extract<T>]
  907. facility in fact solves the mutable copying problem:
  908. dict d = extract<dict>(x.attr("__dict__"));
  909. d["whatever"] = 3; // modifies x.__dict__ !
  910. [endsect]
  911. [section Enums]
  912. Boost.Python has a nifty facility to capture and wrap C++ enums. While
  913. Python has no [^enum] type, we'll often want to expose our C++ enums to
  914. Python as an [^int]. Boost.Python's enum facility makes this easy while
  915. taking care of the proper conversions from Python's dynamic typing to C++'s
  916. strong static typing (in C++, ints cannot be implicitly converted to
  917. enums). To illustrate, given a C++ enum:
  918. enum choice { red, blue };
  919. the construct:
  920. enum_<choice>("choice")
  921. .value("red", red)
  922. .value("blue", blue)
  923. ;
  924. can be used to expose to Python. The new enum type is created in the
  925. current [^scope()], which is usually the current module. The snippet above
  926. creates a Python class derived from Python's [^int] type which is
  927. associated with the C++ type passed as its first parameter.
  928. [note [*what is a scope?]
  929. The scope is a class that has an associated global Python object which
  930. controls the Python namespace in which new extension classes and wrapped
  931. functions will be defined as attributes. Details can be found
  932. [@../reference/high_level_components/boost_python_scope_hpp.html#high_level_components.boost_python_scope_hpp.class_scope here].]
  933. You can access those values in Python as
  934. [python]
  935. >>> my_module.choice.red
  936. my_module.choice.red
  937. where my_module is the module where the enum is declared. You can also
  938. create a new scope around a class:
  939. [c++]
  940. scope in_X = class_<X>("X")
  941. .def( ... )
  942. .def( ... )
  943. ;
  944. // Expose X::nested as X.nested
  945. enum_<X::nested>("nested")
  946. .value("red", red)
  947. .value("blue", blue)
  948. ;
  949. [def Py_Initialize [@http://www.python.org/doc/current/api/initialization.html#l2h-652 Py_Initialize]]
  950. [def Py_Finalize [@http://www.python.org/doc/current/api/initialization.html#l2h-656 Py_Finalize]]
  951. [def Py_XINCREF [@http://www.python.org/doc/current/api/countingRefs.html#l2h-65 Py_XINCREF]]
  952. [def Py_XDECREF [@http://www.python.org/doc/current/api/countingRefs.html#l2h-67 Py_XDECREF]]
  953. [def PyImport_AppendInittab [@http://www.python.org/doc/current/api/importing.html#l2h-137 PyImport_AppendInittab]]
  954. [def PyImport_AddModule [@http://www.python.org/doc/current/api/importing.html#l2h-125 PyImport_AddModule]]
  955. [def PyModule_New [@http://www.python.org/doc/current/api/moduleObjects.html#l2h-591 PyModule_New]]
  956. [def PyModule_GetDict [@http://www.python.org/doc/current/api/moduleObjects.html#l2h-594 PyModule_GetDict]]
  957. [endsect]
  958. [section:creating_python_object Creating `boost::python::object` from `PyObject*`]
  959. When you want a `boost::python::object` to manage a pointer to `PyObject*` pyobj one does:
  960. boost::python::object o(boost::python::handle<>(pyobj));
  961. In this case, the `o` object, manages the `pyobj`, it won’t increase the reference count on construction.
  962. Otherwise, to use a borrowed reference:
  963. boost::python::object o(boost::python::handle<>(boost::python::borrowed(pyobj)));
  964. In this case, `Py_INCREF` is called, so `pyobj` is not destructed when object o goes out of scope.
  965. [endsect] [/ creating_python_object ]
  966. [endsect] [/ Object Interface]
  967. [section Embedding]
  968. By now you should know how to use Boost.Python to call your C++ code from
  969. Python. However, sometimes you may need to do the reverse: call Python code
  970. from the C++-side. This requires you to ['embed] the Python interpreter
  971. into your C++ program.
  972. Currently, Boost.Python does not directly support everything you'll need
  973. when embedding. Therefore you'll need to use the
  974. [@http://www.python.org/doc/current/api/api.html Python/C API] to fill in
  975. the gaps. However, Boost.Python already makes embedding a lot easier and,
  976. in a future version, it may become unnecessary to touch the Python/C API at
  977. all. So stay tuned... :-)
  978. [h2 Building embedded programs]
  979. To be able to embed python into your programs, you have to link to
  980. both Boost.Python's as well as Python's own runtime library.
  981. Boost.Python's library comes in two variants. Both are located
  982. in Boost's [^/libs/python/build/bin-stage] subdirectory. On Windows, the
  983. variants are called [^boost_python.lib] (for release builds) and
  984. [^boost_python_debug.lib] (for debugging). If you can't find the libraries,
  985. you probably haven't built Boost.Python yet. See
  986. [@../../../building.html Building and Testing] on how to do this.
  987. Python's library can be found in the [^/libs] subdirectory of
  988. your Python directory. On Windows it is called pythonXY.lib where X.Y is
  989. your major Python version number.
  990. Additionally, Python's [^/include] subdirectory has to be added to your
  991. include path.
  992. In a Jamfile, all the above boils down to:
  993. [pre
  994. projectroot c:\projects\embedded_program ; # location of the program
  995. # bring in the rules for python
  996. SEARCH on python.jam = $(BOOST_BUILD_PATH) ;
  997. include python.jam ;
  998. exe embedded_program # name of the executable
  999. : #sources
  1000. embedded_program.cpp
  1001. : # requirements
  1002. <find-library>boost_python <library-path>c:\boost\libs\python
  1003. $(PYTHON_PROPERTIES)
  1004. <library-path>$(PYTHON_LIB_PATH)
  1005. <find-library>$(PYTHON_EMBEDDED_LIBRARY) ;
  1006. ]
  1007. [h2 Getting started]
  1008. Being able to build is nice, but there is nothing to build yet. Embedding
  1009. the Python interpreter into one of your C++ programs requires these 4
  1010. steps:
  1011. # '''#include''' [^<boost/python.hpp>]
  1012. # Call Py_Initialize() to start the interpreter and create the [^__main__] module.
  1013. # Call other Python C API routines to use the interpreter.
  1014. [/ # Call Py_Finalize() to stop the interpreter and release its resources.]
  1015. [note [*Note that at this time you must not call Py_Finalize() to stop the
  1016. interpreter. This may be fixed in a future version of boost.python.]
  1017. ]
  1018. (Of course, there can be other C++ code between all of these steps.)
  1019. [:['[*Now that we can embed the interpreter in our programs, lets see how to put it to use...]]]
  1020. [section Using the interpreter]
  1021. As you probably already know, objects in Python are reference-counted.
  1022. Naturally, the [^PyObject]s of the Python C API are also reference-counted.
  1023. There is a difference however. While the reference-counting is fully
  1024. automatic in Python, the Python C API requires you to do it
  1025. [@http://www.python.org/doc/current/c-api/refcounting.html by hand]. This is
  1026. messy and especially hard to get right in the presence of C++ exceptions.
  1027. Fortunately Boost.Python provides the [@../reference/utility_and_infrastructure/boost_python_handle_hpp.html#utility_and_infrastructure.boost_python_handle_hpp.class_template_handle handle] and
  1028. [@../reference/object_wrappers/boost_python_object_hpp.html#object_wrappers.boost_python_object_hpp.class_object object] class templates to automate the process.
  1029. [h2 Running Python code]
  1030. Boost.python provides three related functions to run Python code from C++.
  1031. object eval(str expression, object globals = object(), object locals = object())
  1032. object exec(str code, object globals = object(), object locals = object())
  1033. object exec_file(str filename, object globals = object(), object locals = object())
  1034. eval evaluates the given expression and returns the resulting value.
  1035. exec executes the given code (typically a set of statements) returning the result,
  1036. and exec_file executes the code contained in the given file.
  1037. There are also overloads taking `char const*` instead of str as the first argument.
  1038. The [^globals] and [^locals] parameters are Python dictionaries
  1039. containing the globals and locals of the context in which to run the code.
  1040. For most intents and purposes you can use the namespace dictionary of the
  1041. [^__main__] module for both parameters.
  1042. Boost.python provides a function to import a module:
  1043. object import(str name)
  1044. import imports a python module (potentially loading it into the running process
  1045. first), and returns it.
  1046. Let's import the [^__main__] module and run some Python code in its namespace:
  1047. object main_module = import("__main__");
  1048. object main_namespace = main_module.attr("__dict__");
  1049. object ignored = exec("hello = file('hello.txt', 'w')\n"
  1050. "hello.write('Hello world!')\n"
  1051. "hello.close()",
  1052. main_namespace);
  1053. This should create a file called 'hello.txt' in the current directory
  1054. containing a phrase that is well-known in programming circles.
  1055. [h2 Manipulating Python objects]
  1056. Often we'd like to have a class to manipulate Python objects.
  1057. But we have already seen such a class above, and in the
  1058. [link tutorial.object previous section]: the aptly named [^object] class
  1059. and its derivatives. We've already seen that they can be constructed from
  1060. a [^handle]. The following examples should further illustrate this fact:
  1061. object main_module = import("__main__");
  1062. object main_namespace = main_module.attr("__dict__");
  1063. object ignored = exec("result = 5 ** 2", main_namespace);
  1064. int five_squared = extract<int>(main_namespace["result"]);
  1065. Here we create a dictionary object for the [^__main__] module's namespace.
  1066. Then we assign 5 squared to the result variable and read this variable from
  1067. the dictionary. Another way to achieve the same result is to use eval instead,
  1068. which returns the result directly:
  1069. object result = eval("5 ** 2");
  1070. int five_squared = extract<int>(result);
  1071. [h2 Exception handling]
  1072. If an exception occurs in the evaluation of the python expression,
  1073. [@../reference/high_level_components/boost_python_errors_hpp.html#high_level_components.boost_python_errors_hpp.class_error_already_set error_already_set] is thrown:
  1074. try
  1075. {
  1076. object result = eval("5/0");
  1077. // execution will never get here:
  1078. int five_divided_by_zero = extract<int>(result);
  1079. }
  1080. catch(error_already_set const &)
  1081. {
  1082. // handle the exception in some way
  1083. }
  1084. The [^error_already_set] exception class doesn't carry any information in itself.
  1085. To find out more about the Python exception that occurred, you need to use the
  1086. [@http://www.python.org/doc/api/exceptionHandling.html exception handling functions]
  1087. of the Python C API in your catch-statement. This can be as simple as calling
  1088. [@http://www.python.org/doc/api/exceptionHandling.html#l2h-70 PyErr_Print()] to
  1089. print the exception's traceback to the console, or comparing the type of the
  1090. exception with those of the [@http://www.python.org/doc/api/standardExceptions.html
  1091. standard exceptions]:
  1092. catch(error_already_set const &)
  1093. {
  1094. if (PyErr_ExceptionMatches(PyExc_ZeroDivisionError))
  1095. {
  1096. // handle ZeroDivisionError specially
  1097. }
  1098. else
  1099. {
  1100. // print all other errors to stderr
  1101. PyErr_Print();
  1102. }
  1103. }
  1104. (To retrieve even more information from the exception you can use some of the other
  1105. exception handling functions listed [@http://www.python.org/doc/api/exceptionHandling.html here].)
  1106. [endsect]
  1107. [endsect] [/ Embedding]
  1108. [section Iterators]
  1109. In C++, and STL in particular, we see iterators everywhere. Python also has
  1110. iterators, but these are two very different beasts.
  1111. [*C++ iterators:]
  1112. * C++ has 5 type categories (random-access, bidirectional, forward, input, output)
  1113. * There are 2 Operation categories: reposition, access
  1114. * A pair of iterators is needed to represent a (first/last) range.
  1115. [*Python Iterators:]
  1116. * 1 category (forward)
  1117. * 1 operation category (next())
  1118. * Raises StopIteration exception at end
  1119. The typical Python iteration protocol: [^[*for y in x...]] is as follows:
  1120. [python]
  1121. iter = x.__iter__() # get iterator
  1122. try:
  1123. while 1:
  1124. y = iter.next() # get each item
  1125. ... # process y
  1126. except StopIteration: pass # iterator exhausted
  1127. Boost.Python provides some mechanisms to make C++ iterators play along
  1128. nicely as Python iterators. What we need to do is to produce
  1129. appropriate `__iter__` function from C++ iterators that is compatible
  1130. with the Python iteration protocol. For example:
  1131. [c++]
  1132. object get_iterator = iterator<vector<int> >();
  1133. object iter = get_iterator(v);
  1134. object first = iter.next();
  1135. Or for use in class_<>:
  1136. .def("__iter__", iterator<vector<int> >())
  1137. [*range]
  1138. We can create a Python savvy iterator using the range function:
  1139. * range(start, finish)
  1140. * range<Policies,Target>(start, finish)
  1141. Here, start/finish may be one of:
  1142. * member data pointers
  1143. * member function pointers
  1144. * adaptable function object (use Target parameter)
  1145. [*iterator]
  1146. * iterator<T, Policies>()
  1147. Given a container [^T], iterator is a shortcut that simply calls [^range]
  1148. with &T::begin, &T::end.
  1149. Let's put this into action... Here's an example from some hypothetical
  1150. bogon Particle accelerator code:
  1151. [python]
  1152. f = Field()
  1153. for x in f.pions:
  1154. smash(x)
  1155. for y in f.bogons:
  1156. count(y)
  1157. Now, our C++ Wrapper:
  1158. [c++]
  1159. class_<F>("Field")
  1160. .property("pions", range(&F::p_begin, &F::p_end))
  1161. .property("bogons", range(&F::b_begin, &F::b_end));
  1162. [*stl_input_iterator]
  1163. So far, we have seen how to expose C++ iterators and ranges to Python.
  1164. Sometimes we wish to go the other way, though: we'd like to pass a
  1165. Python sequence to an STL algorithm or use it to initialize an STL
  1166. container. We need to make a Python iterator look like an STL iterator.
  1167. For that, we use `stl_input_iterator<>`. Consider how we might
  1168. implement a function that exposes `std::list<int>::assign()` to
  1169. Python:
  1170. [c++]
  1171. template<typename T>
  1172. void list_assign(std::list<T>& l, object o) {
  1173. // Turn a Python sequence into an STL input range
  1174. stl_input_iterator<T> begin(o), end;
  1175. l.assign(begin, end);
  1176. }
  1177. // Part of the wrapper for list<int>
  1178. class_<std::list<int> >("list_int")
  1179. .def("assign", &list_assign<int>)
  1180. // ...
  1181. ;
  1182. Now in Python, we can assign any integer sequence to `list_int` objects:
  1183. [python]
  1184. x = list_int();
  1185. x.assign([1,2,3,4,5])
  1186. [endsect]
  1187. [section:exception Exception Translation]
  1188. All C++ exceptions must be caught at the boundary with Python code. This
  1189. boundary is the point where C++ meets Python. Boost.Python provides a
  1190. default exception handler that translates selected standard exceptions,
  1191. then gives up:
  1192. raise RuntimeError, 'unidentifiable C++ Exception'
  1193. Users may provide custom translation. Here's an example:
  1194. struct PodBayDoorException;
  1195. void translator(PodBayDoorException const& x) {
  1196. PyErr_SetString(PyExc_UserWarning, "I'm sorry Dave...");
  1197. }
  1198. BOOST_PYTHON_MODULE(kubrick) {
  1199. register_exception_translator<
  1200. PodBayDoorException>(translator);
  1201. ...
  1202. [endsect]
  1203. [section:techniques General Techniques]
  1204. Here are presented some useful techniques that you can use while wrapping code with Boost.Python.
  1205. [section Creating Packages]
  1206. A Python package is a collection of modules that provide to the user a certain
  1207. functionality. If you're not familiar on how to create packages, a good
  1208. introduction to them is provided in the
  1209. [@http://www.python.org/doc/current/tut/node8.html Python Tutorial].
  1210. But we are wrapping C++ code, using Boost.Python. How can we provide a nice
  1211. package interface to our users? To better explain some concepts, let's work
  1212. with an example.
  1213. We have a C++ library that works with sounds: reading and writing various
  1214. formats, applying filters to the sound data, etc. It is named (conveniently)
  1215. [^sounds]. Our library already has a neat C++ namespace hierarchy, like so:
  1216. sounds::core
  1217. sounds::io
  1218. sounds::filters
  1219. We would like to present this same hierarchy to the Python user, allowing him
  1220. to write code like this:
  1221. import sounds.filters
  1222. sounds.filters.echo(...) # echo is a C++ function
  1223. The first step is to write the wrapping code. We have to export each module
  1224. separately with Boost.Python, like this:
  1225. /* file core.cpp */
  1226. BOOST_PYTHON_MODULE(core)
  1227. {
  1228. /* export everything in the sounds::core namespace */
  1229. ...
  1230. }
  1231. /* file io.cpp */
  1232. BOOST_PYTHON_MODULE(io)
  1233. {
  1234. /* export everything in the sounds::io namespace */
  1235. ...
  1236. }
  1237. /* file filters.cpp */
  1238. BOOST_PYTHON_MODULE(filters)
  1239. {
  1240. /* export everything in the sounds::filters namespace */
  1241. ...
  1242. }
  1243. Compiling these files will generate the following Python extensions:
  1244. [^core.pyd], [^io.pyd] and [^filters.pyd].
  1245. [note The extension [^.pyd] is used for python extension modules, which
  1246. are just shared libraries. Using the default for your system, like [^.so] for
  1247. Unix and [^.dll] for Windows, works just as well.]
  1248. Now, we create this directory structure for our Python package:
  1249. [pre
  1250. sounds/
  1251. \_\_init\_\_.py
  1252. core.pyd
  1253. filters.pyd
  1254. io.pyd
  1255. ]
  1256. The file [^\_\_init\_\_.py] is what tells Python that the directory [^sounds/] is
  1257. actually a Python package. It can be a empty file, but can also perform some
  1258. magic, that will be shown later.
  1259. Now our package is ready. All the user has to do is put [^sounds] into his
  1260. [@http://www.python.org/doc/current/tut/node8.html#SECTION008110000000000000000 PYTHONPATH]
  1261. and fire up the interpreter:
  1262. [python]
  1263. >>> import sounds.io
  1264. >>> import sounds.filters
  1265. >>> sound = sounds.io.open('file.mp3')
  1266. >>> new_sound = sounds.filters.echo(sound, 1.0)
  1267. Nice heh?
  1268. This is the simplest way to create hierarchies of packages, but it is not very
  1269. flexible. What if we want to add a ['pure] Python function to the filters
  1270. package, for instance, one that applies 3 filters in a sound object at once?
  1271. Sure, you can do this in C++ and export it, but why not do so in Python? You
  1272. don't have to recompile the extension modules, plus it will be easier to write
  1273. it.
  1274. If we want this flexibility, we will have to complicate our package hierarchy a
  1275. little. First, we will have to change the name of the extension modules:
  1276. [c++]
  1277. /* file core.cpp */
  1278. BOOST_PYTHON_MODULE(_core)
  1279. {
  1280. ...
  1281. /* export everything in the sounds::core namespace */
  1282. }
  1283. Note that we added an underscore to the module name. The filename will have to
  1284. be changed to [^_core.pyd] as well, and we do the same to the other extension modules.
  1285. Now, we change our package hierarchy like so:
  1286. [pre
  1287. sounds/
  1288. \_\_init\_\_.py
  1289. core/
  1290. \_\_init\_\_.py
  1291. \_core.pyd
  1292. filters/
  1293. \_\_init\_\_.py
  1294. \_filters.pyd
  1295. io/
  1296. \_\_init\_\_.py
  1297. \_io.pyd
  1298. ]
  1299. Note that we created a directory for each extension module, and added a
  1300. \_\_init\_\_.py to each one. But if we leave it that way, the user will have to
  1301. access the functions in the core module with this syntax:
  1302. [python]
  1303. >>> import sounds.core._core
  1304. >>> sounds.core._core.foo(...)
  1305. which is not what we want. But here enters the [^\_\_init\_\_.py] magic: everything
  1306. that is brought to the [^\_\_init\_\_.py] namespace can be accessed directly by the
  1307. user. So, all we have to do is bring the entire namespace from [^_core.pyd]
  1308. to [^core/\_\_init\_\_.py]. So add this line of code to [^sounds/core/\_\_init\_\_.py]:
  1309. from _core import *
  1310. We do the same for the other packages. Now the user accesses the functions and
  1311. classes in the extension modules like before:
  1312. >>> import sounds.filters
  1313. >>> sounds.filters.echo(...)
  1314. with the additional benefit that we can easily add pure Python functions to
  1315. any module, in a way that the user can't tell the difference between a C++
  1316. function and a Python function. Let's add a ['pure] Python function,
  1317. [^echo_noise], to the [^filters] package. This function applies both the
  1318. [^echo] and [^noise] filters in sequence in the given [^sound] object. We
  1319. create a file named [^sounds/filters/echo_noise.py] and code our function:
  1320. import _filters
  1321. def echo_noise(sound):
  1322. s = _filters.echo(sound)
  1323. s = _filters.noise(sound)
  1324. return s
  1325. Next, we add this line to [^sounds/filters/\_\_init\_\_.py]:
  1326. from echo_noise import echo_noise
  1327. And that's it. The user now accesses this function like any other function
  1328. from the [^filters] package:
  1329. >>> import sounds.filters
  1330. >>> sounds.filters.echo_noise(...)
  1331. [endsect]
  1332. [section Extending Wrapped Objects in Python]
  1333. Thanks to Python's flexibility, you can easily add new methods to a class,
  1334. even after it was already created:
  1335. >>> class C(object): pass
  1336. >>>
  1337. >>> # a regular function
  1338. >>> def C_str(self): return 'A C instance!'
  1339. >>>
  1340. >>> # now we turn it in a member function
  1341. >>> C.__str__ = C_str
  1342. >>>
  1343. >>> c = C()
  1344. >>> print c
  1345. A C instance!
  1346. >>> C_str(c)
  1347. A C instance!
  1348. Yes, Python rox. :-)
  1349. We can do the same with classes that were wrapped with Boost.Python. Suppose
  1350. we have a class [^point] in C++:
  1351. [c++]
  1352. class point {...};
  1353. BOOST_PYTHON_MODULE(_geom)
  1354. {
  1355. class_<point>("point")...;
  1356. }
  1357. If we are using the technique from the previous session,
  1358. [link tutorial.techniques.creating_packages Creating Packages], we can code directly
  1359. into [^geom/\_\_init\_\_.py]:
  1360. [python]
  1361. from _geom import *
  1362. # a regular function
  1363. def point_str(self):
  1364. return str((self.x, self.y))
  1365. # now we turn it into a member function
  1366. point.__str__ = point_str
  1367. [*All] point instances created from C++ will also have this member function!
  1368. This technique has several advantages:
  1369. * Cut down compile times to zero for these additional functions
  1370. * Reduce the memory footprint to virtually zero
  1371. * Minimize the need to recompile
  1372. * Rapid prototyping (you can move the code to C++ if required without changing the interface)
  1373. Another useful idea is to replace constructors with factory functions:
  1374. _point = point
  1375. def point(x=0, y=0):
  1376. return _point(x, y)
  1377. In this simple case there is not much gained, but for constructurs with
  1378. many overloads and/or arguments this is often a great simplification, again
  1379. with virtually zero memory footprint and zero compile-time overhead for
  1380. the keyword support.
  1381. [endsect]
  1382. [section Reducing Compiling Time]
  1383. If you have ever exported a lot of classes, you know that it takes quite a good
  1384. time to compile the Boost.Python wrappers. Plus the memory consumption can
  1385. easily become too high. If this is causing you problems, you can split the
  1386. class_ definitions in multiple files:
  1387. [c++]
  1388. /* file point.cpp */
  1389. #include <point.h>
  1390. #include <boost/python.hpp>
  1391. void export_point()
  1392. {
  1393. class_<point>("point")...;
  1394. }
  1395. /* file triangle.cpp */
  1396. #include <triangle.h>
  1397. #include <boost/python.hpp>
  1398. void export_triangle()
  1399. {
  1400. class_<triangle>("triangle")...;
  1401. }
  1402. Now you create a file [^main.cpp], which contains the [^BOOST_PYTHON_MODULE]
  1403. macro, and call the various export functions inside it.
  1404. void export_point();
  1405. void export_triangle();
  1406. BOOST_PYTHON_MODULE(_geom)
  1407. {
  1408. export_point();
  1409. export_triangle();
  1410. }
  1411. Compiling and linking together all this files produces the same result as the
  1412. usual approach:
  1413. #include <boost/python.hpp>
  1414. #include <point.h>
  1415. #include <triangle.h>
  1416. BOOST_PYTHON_MODULE(_geom)
  1417. {
  1418. class_<point>("point")...;
  1419. class_<triangle>("triangle")...;
  1420. }
  1421. but the memory is kept under control.
  1422. This method is recommended too if you are developing the C++ library and
  1423. exporting it to Python at the same time: changes in a class will only demand
  1424. the compilation of a single cpp, instead of the entire wrapper code.
  1425. [note This method is useful too if you are getting the error message
  1426. ['"fatal error C1204:Compiler limit:internal structure overflow"] when compiling
  1427. a large source file, as explained in the [@../faq/fatal_error_c1204_compiler_limit.html FAQ].]
  1428. [endsect]
  1429. [endsect] [/ General Techniques]