Debian Codegraph @

doc/tutorial.rst

raw
1
2 =======================
3 PyBindGen Tutorial
4 =======================
5
6
7
8 What is PyBindGen ?
9 ===================
10
11 PyBindGen is a tool which can be used to generate python bindings
12 for C or C++ APIs. It is similar in scope to tools such as boost::python,
13 SWIG, and a few others but has a number of specific features which make
14 it especially useful in a number of cases:
15
16 - PyBindGen is implemented in python and is used and controlled
17 through python;
18 - PyBindGen error messages do not involve c++ template deciphering
19 (as in boost::python);
20 - PyBindGen generates highly-readable C or C++ code so it is
21 possible to step into and debug the bindings;
22 - In simple cases, PyBindGen is really easy to use. In more
23 complicated cases, it does offer all the flexibility you need to
24 wrap complex C or C++ APIs;
25 - PyBindGen also provides an optional tool to parse C and C++
26 headers and generate automatically bindings for them, potentially
27 using extra inline or out-of-line annotations. This tool is based
28 on gccxml and pygccxml: it can be used to generate the first
29 version of the bindings and tweak them by hand later or as a fully
30 automated tool to continuously generate bindings for changing
31 C/C++ APIs.
32
33 This tutorial will show how to build bindings for a couple of common C and C++ API idioms
34 and, then, will proceed to show how to use the automatic binding generator.
35
36
37 Supported Python versions
38 =========================
39
40 PyBindGen officially supports Python versions 2.6, 2.7, and >= 3.3[*] (tested in 3.3 and 3.4).
41
42 PyBindGen does not support Python versions 3.0, 3.1, and 3.2.
43
44 Note that C files generated by PyBindGen transparently support
45 multiple Python versions. In particular, the generated code can build
46 in either Python 2.x or Python 3.x.
47
48 [*] The automatic header file scanning feature of PyBindGen (submodule
49 `pybindgen.gccxmlparser`) does not work in any Python 3.x version,
50 since the pygccxml package has not been ported to Python 3.
51
52
53
54 Work flows
55 ==========
56
57 PyBindGen is only a Python module. The programmer must write a Python
58 script that uses the module in order to generate the bindings. There
59 are several ways that PyBindGen can be used:
60
61 1. Basic mode, script that directly generates the bindings;
62
63 .. image:: figures/work-flow-basic.*
64
65 2. Automatically scan header files and generate the bindings
66 directly (see :ref:`Header file scanning with (py)gccxml<header-file-scanning>`);
67
68 .. image:: figures/work-flow-gccxml.*
69
70 3. Automatically scan header files to generate API defs file, that
71 file can later be used to generate the bindings. See (see
72 :ref:`Header file scanning with (py)gccxml: python intermediate
73 file<header-file-scanning-apidefs>`);
74
75 .. image:: figures/work-flow-gccxml-apidefs.*
76
77
78 A simple example
79 ================
80 The best way to get a feel for what PyBindGen looks like is to go through a
81 simple example.
82
83 Code generation script
84 ----------------------
85
86 Let's assume that we have a simple C API as shown below
87 declared in a header my-module.h:
88
89 .. code-block:: c++
90
91 void MyModuleDoAction (void);
92
93 What we want to do is call this C function from python and be able to write
94 python code such as::
95
96 import MyModule
97
98 MyModule.MyModuleDoAction ()
99
100 Getting there is, hopefully, not very complicated: we just need to write a small
101 python program whose job is to generate the C code which will act as a bridge
102 between our user's python program and the underlying C function. First, we import
103 the pybindgen and the sys modules::
104
105 import pybindgen
106 import sys
107
108 Then, we create an object to represent the module we want to generate::
109
110 mod = pybindgen.Module('MyModule')
111
112 add our C header::
113
114 mod.add_include('"my-module.h"')
115
116 and register our function which returns no value (hence, the second
117 argument 'None'), and, takes no arguments (hence, the third argument,
118 the empty list '[]')::
119
120 mod.add_function('MyModuleDoAction', None, [])
121
122 Finally, we generate code for this binding directed to standard output::
123
124 mod.generate(sys.stdout)
125
126 The final program is pretty short::
127
128 import pybindgen
129 import sys
130
131 mod = pybindgen.Module('MyModule')
132 mod.add_include('"my-module.h"')
133 mod.add_function('MyModuleDoAction', None, [])
134 mod.generate(sys.stdout)
135
136 Building it using Python setup.py (distutils)
137 ---------------------------------------------
138
139 This very small example is located in the :download:`first-example
140 directory <_static/first-example.zip>`, together with a small makefile which
141 will build our extension module::
142
143 $ cd first-example/
144 $ python setup.py build
145
146 The `setup.py` is mostly a standard Python distutils driver script.
147 Please refer to the `Python documentation
148 <http://docs.python.org/3/extending/building.html>`_ for more
149 information.
150
151 The unusual part about this `setup.py` is that it imports
152 `mymodulegen` and calls the generate function, with the
153 `build/my-module-binding.c` as argument::
154
155 from mymodulegen import generate
156 module_fname = os.path.join("build", "my-module-binding.c")
157 with open(module_fname, "wt") as file_:
158 print("Generating file {}".format(module_fname))
159 generate(file_)
160
161 After `build/my-module-binding.c` having been generated, with the help
162 of PyBindGen (as seen in the previous section), we can use it as one
163 of the source files for our extension module::
164
165 mymodule = Extension('mymodule',
166 sources = [module_fname, 'my-module.c'],
167 include_dirs=['.'])
168
169 The rest is standard setup.py code.
170
171
172 Testing it
173 ----------
174
175 Once all of that code is built, we obviously want to run it. Setting up
176 your system to make sure that the python module is found by the python runtime
177 is outside the scope of this tutorial but, for most people, the following session
178 should be self-explanatory::
179
180 $ cd first-example/
181 $ python setup.py buid
182 Generating file build/my-module-binding.c
183 running build
184 running build_ext
185 building 'mymodule' extension
186 creating build/temp.linux-x86_64-2.7
187 creating build/temp.linux-x86_64-2.7/build
188 [...]
189 $ export PYTHONPATH=build/lib.linux-x86_64-2.7/
190 $ python
191 Python 2.7.5+ (default, Sep 19 2013, 13:48:49)
192 [GCC 4.8.1] on linux2
193 Type "help", "copyright", "credits" or "license" for more information.
194 >>> import mymodule
195 >>> mymodule.MyModuleDoAction ()
196 You called MyModuleDoAction !
197 >>>
198
199
200 Wrapping types by value
201 =======================
202
203 Primitive types
204 ---------------
205
206 The first example showed how to call a function which takes no
207 arguments and returns no values which, obviously, is not especially
208 interesting so, let's look at how we can give meaningfull arguments
209 to our function:
210
211 .. code-block:: c++
212
213 int MyModuleDoAction (int v1, int v2);
214
215 and the corresponding bit from the code generation script: the second
216 argument to add_function specifies that our function returns a value of type
217 'int' and the third argument specifies that our function takes as a
218 single argument an 'int' of name 'value'::
219
220 mod.add_function('MyModuleDoAction',
221 pybindgen.retval ('int'),
222 [pybindgen.param ('int', 'v1'),
223 pybindgen.param ('int', 'v2')])
224
225 The above then allows you to write::
226
227 >>> import MyModule
228 >>> v = MyModule.MyModuleDoAction (10, -1)
229 You called MyModuleDoAction: 10
230 >>> print v
231 10
232 >>> v = MyModule.MyModuleDoAction (v2=5, v1=-2)
233 You called MyModuleDoAction: -2
234 >>> print v
235 -2
236
237 Which shows how the argument name can be used to avoid
238 using positional arguments.
239
240
241 Of course, the above example could be rewritten to the more compact and readable::
242
243 from pybindgen import *
244 mod.add_function('MyModuleDoAction', retval ('int'),
245 [param ('int', 'v1'),
246 param ('int', 'v2')])
247
248 In the following examples, this is what we will do to avoid extra typing.
249
250
251 Enum types
252 ----------
253
254 Enums are often used to define C and C++ constants as shown below:
255
256 .. code-block:: c++
257
258 enum MyEnum_e
259 {
260 CONSTANT_A,
261 CONSTANT_B,
262 CONSTANT_C
263 };
264 void MyModuleDoAction (enum enum_e value);
265
266 And wrapping them is also pretty trivial::
267
268 from pybindgen import *
269 import sys
270
271 mod = Module('MyModule')
272 mod.add_include('"my-module.h"')
273 mod.add_enum('MyEnum_e', ['CONSTANT_A', 'CONSTANT_B', 'CONSTANT_C'])
274 mod.add_function('MyModuleDoAction', None, [param('MyEnum_e', 'value')])
275 mod.generate(sys.stdout)
276
277 With the resulting python-visible API::
278
279 >>> import MyModule
280 >>> print MyModule.CONSTANT_A
281 0
282 >>> print MyModule.CONSTANT_B
283 1
284 >>> print MyModule.CONSTANT_C
285 2
286 >>> MyModule.MyModuleDoAction (MyModule.CONSTANT_B)
287 MyModuleDoAction: 1
288
289 Compound types
290 --------------
291
292 Passing a structure to and from C is not really more complicated than
293 our previous example. The API below:
294
295 .. code-block:: c++
296
297 struct MyModuleStruct
298 {
299 int a;
300 int b;
301 };
302 struct MyModuleStruct MyModuleDoAction (struct MyModuleStruct value);
303
304 can be bound to python using the following script::
305
306 from pybindgen import *
307 import sys
308
309 mod = Module('MyModule')
310 mod.add_include('"my-module.h"')
311 struct = mod.add_struct('MyModuleStruct')
312 struct.add_instance_attribute('a', 'int')
313 struct.add_instance_attribute('b', 'int')
314 mod.add_function('MyModuleDoAction', retval ('MyModuleStruct'), [param ('MyModuleStruct', 'value')])
315 mod.generate(sys.stdout)
316
317 The most obvious change here is that we have to define the new structure type::
318
319 struct = mod.add_struct('MyModuleStruct')
320
321 and register the names and types of each of the members we want to make accessible
322 from python::
323
324 struct.add_instance_attribute('a', 'int')
325 struct.add_instance_attribute('b', 'int')
326
327 The name of the method called here, 'add_instance_attribute' reflects the fact that
328 PyBindGen can wrap both C and C++ APIs: in C++, there exist both instance and static
329 members so, PyBindGen provides two methods: add_instance_attribute and add_static_attribute
330 to register these two kinds of members.
331
332 Our C API then becomes accessible from python::
333 >>> import MyModule
334 >>> st = MyModule.MyModuleStruct ()
335 >>> st.a = 10
336 >>> st.b = -20
337 >>> st.c = -10
338 Traceback (most recent call last):
339 File "<stdin>", line 1, in <module>
340 AttributeError: 'MyModule.MyModuleStruct' object has no attribute 'c'
341 >>> v = MyModule.MyModuleDoAction (st)
342 You called MyModuleDoAction: 10
343 >>> print v
344 <MyModule.MyModuleStruct object at 0x2b5ef522b150>
345 >>> print v.a
346 10
347 >>> print v.b
348 -20
349
350
351 C++ classes
352 -----------
353
354 Wrapping C++ classes is very similar to wrapping a C struct with a few functions: we will thus
355 start by extending our C API with a C++ class declaration:
356
357 .. code-block:: c++
358
359 class MyClass
360 {
361 public:
362 void SetInt (int value);
363 int GetInt (void) const;
364 };
365
366 We first need to declare a C++ class::
367
368 mod = Module('MyModule')
369 klass = mod.add_class('MyClass')
370
371 and, then, specify that it has a constructor::
372
373 klass.add_constructor([])
374
375 We can declare the setter method which is really
376 a straightforward extension from the add_function function::
377
378 klass.add_method('SetInt', None, [param('int', 'value')])
379
380 The getter is also pretty straightforward except for the declaration
381 of constness::
382
383 klass.add_method('GetInt', retval('int'), [], is_const=True)
384
385 Using this API is also very similar to the struct example we went through
386 in the previous section::
387
388 >>> my = MyModule.MyClass()
389 >>> my.SetInt(10)
390 >>> v = my.GetInt()
391 >>> print v
392 10
393
394 It is also possible to bind inner classes and enums such
395 as these:
396
397 .. code-block:: c++
398
399 class Outer
400 {
401 public:
402 void Do (void);
403 // an inner enum
404 enum inner_e
405 {
406 INNER_A,
407 INNER_B,
408 INNER_C
409 };
410 // an inner class
411 class Inner
412 {
413 public:
414 void Do (enum Outer::inner_e value);
415 };
416 };
417
418 We just need to bind the outer class::
419
420 outer = mod.add_class('Outer')
421 outer.add_constructor([])
422 outer.add_method('Do', None, [])
423
424 Then, bind its inner enum::
425
426 mod.add_enum('inner_e', ['INNER_A', 'INNER_B', 'INNER_C'], outer_class=outer)
427
428 and, finally, bind its inner class::
429
430 mod.add_class('Inner', outer_class=outer)
431 inner.add_constructor([])
432
433 The only slightly tricky part is binding the Do method of the Inner
434 class since it refers to the enum type defined in the Outer class: we
435 simply need to carefully use the fully scoped name of the enum.::
436
437 inner.add_method('Do', None, [param('Outer::inner_e', value)])
438
439 The resulting python API reflects the underlying C++ API very closely::
440
441 >>> import MyModule
442 >>> print MyModule.Outer.INNER_A
443 0
444 >>> print MyModule.Outer.INNER_B
445 1
446 >>> outer = MyModule.Outer()
447 >>> outer.Do()
448 >>> inner = MyModule.Outer.Inner()
449 >>> inner.Do(MyModule.Outer.INNER_A)
450
451
452 C++ namespaces
453 --------------
454
455 Wrapping multiple nested namespaces is, of course, possible and represents
456 no special challenge. Let's look at an example:
457
458 .. code-block:: c++
459
460 namespace Outer {
461 void Do (void);
462 class MyClass
463 {};
464 namespace Inner {
465 void Do (void);
466 class MyClass
467 {};
468 } // namespace Inner
469 } // namespace Outer
470
471 First, we need to define the Outer namespace::
472
473 mod = Module('MyModule')
474 outer = mod.add_cpp_namespace('Outer')
475
476 Then, register its classes and functions::
477
478 outer.add_class('MyClass')
479 outer.add_function('Do', None, [])
480
481 and, finally, define the Inner namespace and its associated
482 functions and methods::
483
484 inner = outer.add_cpp_namespace('Inner')
485 inner.add_class('MyClass')
486 inner.add_function('Do', None, [])
487
488 The resulting API, again, sticks to the underlying C++ API by
489 defining one python module for each C++ namespace and making
490 sure that the hierarchy of python modules matches the hierarchy
491 of C++ namespaces::
492
493 >>> import MyModule
494 >>> o = MyModule.Outer.MyClass()
495 >>> i = MyModule.Outer.Inner.MyClass()
496 >>> from MyModule.Outer.Inner import *
497 >>> i = MyClass()
498
499
500 Memory management for pointer types
501 ===================================
502
503 Until then, we have shown how to pass back and forth data through C/C++ APIs
504 only by value but, a large fraction of real-world APIs use raw pointers
505 (and, in the case of C++, smart pointers) as arguments or return values
506 of functions/methods.
507
508 Rather than try to explain the detail of every option offered by PyBindGen
509 to deal with pointers, we will go through a couple of very classic memory
510 management schemes and examples.
511
512 Function returns pointer
513 ------------------------
514
515 The API to bind:
516
517 .. code-block:: c++
518
519 class MyClass;
520 MyClass *DoSomethingAndReturnClass (void);
521
522 First, we declare the MyClass type::
523
524 mod.add_class('MyClass')
525 ...
526
527 Then, if we assume that the function returns ownership of the pointer to the caller, we
528 can write::
529
530 mod.add_function('DoSomethingAndReturnClass', retval('MyClass *', caller_owns_return=True), [])
531
532 The above will tell PyBindGen that the caller (the python runtime) becomes
533 responsible for deleting the instance of MyClass returned by the function
534 DoSomethingAndReturnClass when it is done with it.
535
536 Of course, it is possible to not give back ownership of the returned pointer
537 to the caller::
538
539 mod.add_function('DoSomethingAndReturnClass', retval('MyClass *', caller_owns_return=False), [])
540
541 Which would make the python runtime assume that the lifetime of the returned pointer
542 is longer than the associated python object.
543
544 Function takes pointer
545 ----------------------
546
547 The API to bind:
548
549 .. code-block:: c++
550
551 class MyClass;
552 void DoWithClass (MyClass *cls);
553
554 If we assume that the callee takes ownership of the input pointer, we can write::
555
556 mod.add_function('DoWithClass', None, [param('MyClass *', 'cls', transfer_ownership=True)])
557
558 Which will make python keep a handle on the MyClass instance but never destroy it himself
559 and rely on the callee to destroy it at the right time. This kind of scheme is obviously
560 a bit dangerous because python has no way of knowing when the underlying MyClass instance
561 is really destroyed so, if you try to invoke methods on it _after_ it has been destroyed,
562 bad things will obviously happen.
563
564 If, instead, we assume that the caller keeps ownership of the pointer, we can write
565 the much safer version::
566
567 mod.add_function('DoWithClass', None, [param('MyClass *', 'cls', transfer_ownership=False)])
568
569 Which will allow python to delete the MyClass instance only when the associated python wrapper
570 disappears.
571
572 A reference-counted object
573 --------------------------
574
575 A nice way to avoid some of the ambiguities of the above-mentioned API bindings is to
576 use reference-counted C or C++ objects which must provide a pair of functions or methods
577 to increase or decrease the reference count of the object. For example, a classic
578 C++ reference-counted class:
579
580 .. code-block:: c++
581
582 class MyClass
583 {
584 public:
585 void Ref (void);
586 void Unref (void);
587 uint32_t PeekRef (void);
588 };
589
590 And the associated function which takes a pointer:
591
592 .. code-block:: c++
593
594 void DoSomething (MyClass *cls);
595
596 To wrap this class, we first need to declare our class::
597
598 from pybindgen import cppclass
599 [...]
600 mod.add_class('MyClass', memory_policy=cppclass.ReferenceCountingMethodsPolicy(
601 incref_method='Ref',
602 decref_method='Unref',
603 peekref_method='PeekRef'))
604
605 The above allows PyBindGen to maintain and track the reference count
606 of the MyClass object while the code below shows how we can declare
607 a function taking a pointer as input::
608
609 mod.add_function('DoSomething', None, [param('MyClass *', 'cls', transfer_ownership=False)]
610
611 Here, the meaning of transfer_ownership changes slightly.
612 Whithout reference counting, transfer_ownership refers to the
613 transfer of the object as a whole, i.e. either the caller or
614 callee will own the object in the end, but not both. With
615 reference counting, transfer_ownership refers to the transfer of a
616 _reference_. In this example, transfer_ownership=False means that
617 the caller will not "steal" our reference, i.e. it will either not
618 keep a reference to our object for itself, or if it does it
619 creates its own reference to the object by calling the incref
620 method. If transfer_ownership=True it would mean that the caller
621 would keep the passed in reference to itself, and if the caller
622 wants to keep the reference it must call the incref method first.
623
624 A more interesting case is that of returning such a reference counted
625 object from a function:
626
627 .. code-block:: c++
628
629 MyClass *DoSomething (void);
630
631 While classic reference counting rules require that the callee returns
632 a reference to the caller (i.e., it calls Ref on behalf of the caller
633 before returning the pointer), some APIs will undoubtedly return a pointer
634 and expect the caller to acquire a reference to the returned object by
635 calling Ref himself. PyBindGen hopefully can be made to support this
636 case too::
637
638 mod.add_function('DoSomething', retval('MyClass *', caller_owns_return=False), [])
639
640 Which instructs PyBindGen that DoSomething is not to be trusted and that it should
641 acquire ownership of the returned pointer if it needs to keep track of it.
642
643
644 A STL container
645 ---------------
646
647 If you have a function that takes a STL container, you have to
648 tell PyBindGen to wrap the container first:
649
650 .. code-block:: c++
651
652 void DoSomething (std::list<std::string> const &listOfStrings);
653
654 Is wrapped by::
655
656 module.add_container('std::list<std::string>', 'std::string', 'list') # declare a container only once
657 [...]
658 mod.add_function('DoSomething', None, [param('std::list<std::string> const &', 'listOfStrings')])
659
660
661 .. Subclassing a C++ class from python
662 .. ===================================
663
664 .. Extending a C++ class or namespace from python
665 .. ==============================================
666
667
668 Advanced usage
669 ==============
670
671
672 Basic interface with error handling
673 -----------------------------------
674
675 It is also possible to declare a error handler. The error handler
676 will be invoked for API definitions that cannot be wrapped for some
677 reason::
678
679 #! /usr/bin/env python
680
681 import sys
682
683 import pybindgen
684 from pybindgen import Module, FileCodeSink, retval, param
685
686 import pybindgen.settings
687 import warnings
688
689 class ErrorHandler(pybindgen.settings.ErrorHandler):
690 def handle_error(self, wrapper, exception, traceback_):
691 warnings.warn("exception %r in wrapper %s" % (exception, wrapper))
692 return True
693 pybindgen.settings.error_handler = ErrorHandler()
694
695
696 def my_module_gen(out_file):
697 pybindgen.write_preamble(FileCodeSink(out_file))
698
699 mod = Module('a')
700 mod.add_include('"a.h"')
701
702 mod.add_function('ADoA', None, [])
703 mod.add_function('ADoB', None, [param('uint32_t', 'b')])
704 mod.add_function('ADoC', retval('uint32_t'), [])
705
706 mod.generate(FileCodeSink(out_file) )
707
708 if __name__ == '__main__':
709 my_module_gen(sys.stdout)
710
711 In this example, we register a error handler that allows PyBindGen
712 to simply ignore API definitions with errors, and not wrap them, but
713 move on.
714
715 The difference between is Parameter.new(...) and param(...), as well
716 as between ReturnValue.new(...) and retval(...) is to be noted here.
717 The main difference is not that param(...) and retval(...) are
718 shorter, it is that they allow delayed error handling. For example,
719 when you put Parameter.new("type that does not exist", "foo") in
720 your python script, a TypeLookupError exception is raised and it is
721 not possible for the error handler to catch it. However, param(...)
722 does not try to lookup the type handler immediately and instead lets
723 Module.add_function() do that in a way that the error handler can be
724 invoked and the function is simply not wrapped if the error handler
725 says so.
726
727 .. _header-file-scanning:
728
729 Header file scanning with (py)gccxml
730 ------------------------------------
731
732 If you have gccxml and pygccxml installed, PyBindGen can use them to
733 scan the API definitions directly from the header files::
734
735 #! /usr/bin/env python
736
737 import sys
738
739 import pybindgen
740 from pybindgen import FileCodeSink
741 from pybindgen.gccxmlparser import ModuleParser
742
743 def my_module_gen():
744 module_parser = ModuleParser('a1', '::')
745 module = module_parser.parse([sys.argv[1]])
746 module.add_include('"a.h"')
747
748 pybindgen.write_preamble(FileCodeSink(sys.stdout))
749 module.generate(FileCodeSink(sys.stdout))
750
751 if __name__ == '__main__':
752 my_module_gen()
753
754 The above script will generate the bindings for the module directly.
755 It expects the input header file, a.h, as first command line
756 argument.
757
758 .. _header-file-scanning-apidefs:
759
760 Header file scanning with (py)gccxml: python intermediate file
761 --------------------------------------------------------------
762
763 The final code generation flow supported by PyBindGen is a hybrid of
764 the previous ones. One script scans C/C++ header files, but instead
765 of generating C/C++ binding code directly it instead generates a
766 PyBindGen based Python script::
767
768 #! /usr/bin/env python
769
770 import sys
771
772 from pybindgen import FileCodeSink
773 from pybindgen.gccxmlparser import ModuleParser
774
775 def my_module_gen():
776 module_parser = ModuleParser('a2', '::')
777 module_parser.parse([sys.argv[1]], includes=['"a.h"'], pygen_sink=FileCodeSink(sys.stdout))
778
779 if __name__ == '__main__':
780 my_module_gen()
781
782 The above script produces a Python program on stdout. Running the
783 generated Python program will, in turn, generate the C++ code
784 binding our interface.
785