Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: downloads/boost_1_34_1/libs/python/pyste/doc/pyste.txt @ 29

Last change on this file since 29 was 29, checked in by landauf, 17 years ago

updated boost from 1_33_1 to 1_34_1

File size: 21.1 KB
Line 
1[doc Pyste Documentation]
2
3[/ Copyright 2003 Bruno da Silva de Oliveira and Joel de Guzman.
4Distributed under the Boost Software License, Version 1.0. (See
5accompanying file LICENSE_1_0.txt or copy at
6http://www.boost.org/LICENSE_1_0.txt) ]
7
8[def GCCXML             [@http://www.gccxml.org GCCXML]]
9[def Boost.Python       [@../../index.html Boost.Python]]
10
11[page Introduction]
12
13[h2 What is Pyste?]
14
15Pyste is a Boost.Python code generator. The user specifies the classes and
16functions to be exported using a simple ['interface file], which following the
17Boost.Python's philosophy, is simple Python code. Pyste then uses GCCXML to
18parse all the headers and extract the necessary information to automatically
19generate C++ code.
20
21[h2 Example]
22
23Let's borrow the class [^World] from the [@../../doc/tutorial/doc/exposing_classes.html tutorial]:
24
25    struct World
26    {
27        void set(std::string msg) { this->msg = msg; }
28        std::string greet() { return msg; }
29        std::string msg;
30    };
31
32Here's the interface file for it, named [^world.pyste]:
33
34    Class("World", "world.h")
35
36and that's it!
37
38The next step is invoke Pyste in the command-line:
39
40[pre python pyste.py --module=hello world.pyste]
41
42this will create a file "[^hello.cpp]" in the directory where the command was
43run.
44
45Pyste supports the following features:
46
47* Functions
48* Classes
49* Class Templates
50* Virtual Methods
51* Overloading
52* Attributes
53* Enums (both "free" enums and class enums)
54* Nested Classes
55* Support for [^boost::shared_ptr] and [^std::auto_ptr]
56* Global Variables
57
58[page Running Pyste]
59
60To run Pyste, you will need:
61
62* Python 2.2, available at [@http://www.python.org python's website].
63* The great [@http://effbot.org elementtree] library, from Fredrik Lundh.
64* The excellent GCCXML, from Brad King.
65
66Installation for the tools is available in their respective webpages.
67
68[blurb
69[$theme/note.gif] GCCXML must be accessible in the PATH environment variable, so
70that Pyste can call it. How to do this varies from platform to platform.
71]
72
73[h2 Ok, now what?]
74
75Well, now let's fire it up:
76
77[pre
78'''
79>python pyste.py
80
81Pyste version 0.9.26
82
83Usage:
84    pyste [options] interface-files
85
86where options are:
87    --module=<name>         The name of the module that will be generated;
88                            defaults to the first interface filename, without
89                            the extension.
90    -I <path>               Add an include path
91    -D <symbol>             Define symbol
92    --multiple              Create various cpps, instead of only one
93                            (useful during development)
94    --out=<name>            Specify output filename (default: <module>.cpp)
95                            in --multiple mode, this will be a directory
96    --no-using              Do not declare "using namespace boost";
97                            use explicit declarations instead
98    --pyste-ns=<name>       Set the namespace where new types will be declared;
99                            default is the empty namespace
100    --debug                 Writes the xml for each file parsed in the current
101                            directory
102    --cache-dir=<dir>       Directory for cache files (speeds up future runs)
103    --only-create-cache     Recreates all caches (doesn't generate code).
104    --generate-main         Generates the _main.cpp file (in multiple mode)
105    --file-list             A file with one pyste file per line. Use as a
106                            substitute for passing the files in the command
107                            line.
108    -h, --help              Print this help and exit
109    -v, --version           Print version information
110 
111'''                       
112]
113
114Options explained:
115
116The [^-I] and [^-D] are preprocessor flags, which are needed by GCCXML to parse
117the header files correctly and by Pyste to find the header files declared in the
118interface files.
119
120[^--out] names the output file (default: [^<module>.cpp]), or in multiple mode,
121names a output directory for the files (default: [^<module>]).
122
123[^--no-using] tells Pyste to don't declare "[^using namespace boost;]" in the
124generated cpp, using the namespace boost::python explicitly in all declarations.
125Use only if you're having a name conflict in one of the files.
126
127Use [^--pyste-ns] to change the namespace where new types are declared (for
128instance, the virtual wrappers). Use only if you are having any problems. By
129default, Pyste uses the empty namespace.
130
131[^--debug] will write in the current directory a xml file as outputted by GCCXML
132for each header parsed. Useful for bug reports.
133
134[^--file-list] names a file where each line points to a Pyste file. Use this instead
135to pass the pyste files if you have a lot of them and your shell has some command line
136size limit.
137
138The other options are explained below, in [@#multiple_mode [*Multiple Mode]] and
139[@#cache [*Cache]].
140
141[^-h, --help, -v, --version] are self-explaining, I believe. ;)
142
143So, the usage is simple enough:
144
145[pre >python pyste.py --module=mymodule file.pyste file2.pyste ...]
146
147will generate a file [^mymodule.cpp] in the same dir where the command was
148executed. Now you can compile the file using the same instructions of the
149[@../../doc/tutorial/doc/building_hello_world.html tutorial].
150
151[h2 Wait... how do I set those I and D flags?]
152
153Don't worry: normally GCCXML is already configured correctly for your plataform,
154so the search path to the standard libraries and the standard defines should
155already be set. You only have to set the paths to other libraries that your code
156needs, like Boost, for example.
157
158Plus, Pyste automatically uses the contents of the environment variable
159[^INCLUDE] if it exists. Visual C++ users should run the [^Vcvars32.bat] file,
160which for Visual C++ 6 is normally located at:
161
162    C:\Program Files\Microsoft Visual Studio\VC98\bin\Vcvars32.bat
163
164with that, you should have little trouble setting up the flags.
165
166[blurb [$theme/note.gif][*A note about Psyco][br][br]
167Although you don't have to install [@http://psyco.sourceforge.net/ Psyco] to
168use Pyste, if you do, Pyste will make use of it to speed up the wrapper
169generation. Speed ups of 30% can be achieved, so it's highly recommended.
170]
171
172
173[h2 Multiple Mode]
174
175The multiple mode is useful in large projects, where the presence of multiple
176classes in a single file makes the compilation unpractical (excessive memory
177usage, mostly).
178
179The solution is make Pyste generate multiple files, more specifically one cpp
180file for each Pyste file. This files will contain a function named after the
181file, for instance Export_MyPysteFile, which will contain all the code to export
182the classes, enums, etc. You can pass as much files as you want this way:
183
184[pre >python pyste.py --module=mymodule file1.pyste file2.pyste]
185
186This will create the files [^mymodule/file1.cpp] and [^mymodule/file2.cpp]. You
187can then later do:
188
189[pre >python pyste.py --module=mymodule file3.pyste]
190
191and [^mymodule/file3.cpp] will be generated.
192
193But compiling and linking this files won't be sufficient to generate your
194extension. You have to also generate a file named [^main.cpp]; call pyste with
195[*all] the Pyste files of your extension, and use the [^--generate-main] option:
196
197[pre >python pyste.py --module=mymodule --generate-main file1.pyste file2.pyste file3.pyste]
198
199Now compile and link all this files together and your extension is ready for
200use.
201
202[h2 Cache]
203
204Pyste now supports a form of cache, which is a way to speed up the code
205generation. Most of the time that Pyste takes to generate the code comes from
206having to execute GCCXML (since being a front-end to GCC, it has to compile the
207header files) and reading back the XML generated.
208
209When you use the [^--cache-dir=<dir>] option, Pyste will dump in the specified
210directory the generated XMLs to a file named after the Pyste file, with the
211extension [^.pystec].  The next time you run with this option, Pyste will use
212the cache, instead of calling GCCXML again:
213
214[pre >python pyste.py --module=mymodule --cache-dir=cache file1.pyste]
215
216Will generate [^file1.cpp] and [^cache/file1.pystec]. Next time you execute
217this command, the cache file will be used. Note that Pyste doesn't do any check
218to ensure that the cache is up to date, but you can configure your build system to do that for you.
219
220When you run Pyste with [^--only-create-cache], all the cache files will be
221created again, but no code will be generated.
222
223[page The Interface Files]
224
225The interface files are the heart of Pyste. The user creates one or more
226interface files declaring the classes and functions he wants to export, and then
227invokes Pyste passing the interface files to it. Pyste then generates a single
228cpp file with Boost.Python code, with all the classes and functions exported.
229
230Besides declaring the classes and functions, the user has a number of other
231options, like renaming e excluding classes and member functionis. Those are
232explained later on.
233
234[h2 Basics]
235
236Suppose we have a class and some functions that we want to expose to Python
237declared in the header [^hello.h]:
238
239    struct World
240    {
241        World(std::string msg): msg(msg) {}
242        void set(std::string msg) { this->msg = msg; }
243        std::string greet() { return msg; }
244        std::string msg;
245    };
246
247    enum choice { red, blue };
248   
249    namespace test {
250   
251    void show(choice c) { std::cout << "value: " << (int)c << std::endl; }
252   
253    }
254
255We create a file named [^hello.pyste] and create instances of the classes
256[^Function], [^Class] and [^Enum]:
257
258    Function("test::show", "hello.h")
259    Class("World", "hello.h")
260    Enum("choice", "hello.h")
261
262That will expose the class, the free function and the enum found in [^hello.h].
263
264[h2 Inheritance]
265
266Pyste automatically generates the correct code (specifying [^bases<>] in the
267[^class_] declaration) [*if] the Class() function that exports the base classes
268and their children are in the same Pyste file. If that's not the case, you have
269to indicate that there's a relationship between the Pyste files using the
270[^Import] function specifying the other Pyste file.
271
272Suppose we have two classes, [^A] and [^B], and A is a base class for B. We
273create two Pyste files:
274
275[^A.pyste]:
276
277    Class("A", "A.h")
278
279[^B.pyste]:
280
281    Import("A.pyste")
282    Class("B", "B.h")
283
284Note that we specify that [^B] needs to know about [^A] to be properly exported.
285
286[page:1 Renaming and Excluding]
287
288You can easily rename functions, classes, member functions, attributes, etc. Just use the
289function [^rename], like this:
290
291    World = Class("World", "hello.h")
292    rename(World, "IWorld")
293    show = Function("choice", "hello.h")
294    rename(show, "Show")
295
296You can rename member functions and attributes using this syntax:
297
298    rename(World.greet, "Greet")
299    rename(World.set, "Set")
300    choice = Enum("choice", "hello.h")
301    rename(choice.red, "Red")
302    rename(choice.blue, "Blue")
303
304You can exclude functions, classes, member functions, attributes, etc, in the same way,
305with the function [^exclude]:
306
307    exclude(World.greet)
308    exclude(World.msg)
309
310To access the operators of a class, access the member [^operator] like this
311(supposing that [^C] is a class being exported):
312
313    exclude(C.operator['+'])
314    exclude(C.operator['*'])
315    exclude(C.operator['<<'])
316
317The string inside the brackets is the same as the name of the operator in C++.[br]
318
319[h2 Virtual Member Functions]
320
321Pyste automatically generates wrappers for virtual member functions, but you may
322want to disable this behaviour (for performance reasons, for instance) if you do
323not plan to override the functions in Python. To do this, use the function
324[^final]:
325
326    C = Class('C', 'C.h')
327    final(C.foo) # C::foo is a virtual member function
328
329No virtual wrapper code will be generated for the virtual member function
330C::foo that way.
331
332[page:1 Policies]
333
334Even thought Pyste can identify various elements in the C++ code, like virtual
335member functions, attributes, and so on, one thing that it can't do is to
336guess the semantics of functions that return pointers or references. In this
337case, the user must manually specify the policy. Policies are explained in the
338[@../../doc/tutorial/doc/call_policies.html tutorial].
339
340The policies in Pyste are named exactly as in Boost.Python, only the syntax is
341slightly different. For instance, this policy:
342
343    return_internal_reference<1, with_custodian_and_ward<1, 2> >()
344
345becomes in Pyste:   
346
347    return_internal_reference(1, with_custodian_and_ward(1, 2))
348
349The user can specify policies for functions and virtual member functions with
350the [^set_policy] function:
351
352    set_policy(f, return_internal_reference())
353    set_policy(C.foo, return_value_policy(manage_new_object))
354
355[blurb
356[$theme/note.gif] [*What if a function or member function needs a policy and
357the user doesn't set one?][br][br] If a function needs a policy and one
358was not set, Pyste will issue a error.  The user should then go in the
359interface file and set the policy for it, otherwise the generated cpp won't
360compile.
361]
362
363[blurb
364[$theme/note.gif]
365Note that for functions that return [^const T&], the policy
366[^return_value_policy<copy_const_reference>()] wil be used by default, because
367that's normally what you want. You can change it to something else if you need
368to, though.
369]
370
371[page:1 Templates]
372
373Template classes can easily be exported too, but you can't export the template
374itself... you have to export instantiations of it! So, if you want to export a
375[^std::vector], you will have to export vectors of int, doubles, etc.
376
377Suppose we have this code:
378
379    template <class T>
380    struct Point
381    {
382        T x;
383        T y;
384    };
385
386And we want to export [^Point]s of int and double:
387
388    Point = Template("Point", "point.h")
389    Point("int")
390    Point("double")
391
392Pyste will assign default names for each instantiation. In this example, those
393would be "[^Point_int]" and "[^Point_double]", but most of the time users will want to
394rename the instantiations:
395
396    Point("int", "IPoint")         // renames the instantiation
397    double_inst = Point("double")  // another way to do the same
398    rename(double_inst, "DPoint")
399
400Note that you can rename, exclude, set policies, etc, in the [^Template] object
401like you would do with a [^Function] or a [^Class]. This changes affect all
402[*future] instantiations:
403
404    Point = Template("Point", "point.h")
405    Point("float", "FPoint")        // will have x and y as data members
406    rename(Point.x, "X")
407    rename(Point.y, "Y")
408    Point("int", "IPoint")          // will have X and Y as data members
409    Point("double", "DPoint")       // also will have X and Y as data member
410
411If you want to change a option of a particular instantiation, you can do so:
412
413    Point = Template("Point", "point.h")
414    Point("int", "IPoint")         
415    d_inst = Point("double", "DPoint")       
416    rename(d_inst.x, "X")           // only DPoint is affect by this renames,
417    rename(d_inst.y, "Y")           // IPoint stays intact
418
419[blurb [$theme/note.gif] [*What if my template accepts more than one type?]
420[br][br]
421When you want to instantiate a template with more than one type, you can pass
422either a string with the types separated by whitespace, or a list of strings
423'''("int double" or ["int", "double"]''' would both work).
424]
425
426[page:1 Wrappers]
427
428Suppose you have this function:
429
430    std::vector<std::string> names();
431
432But you don't want to [@../../doc/v2/faq.html#question2 to export std::vector<std::string>],
433you want this function to return a python list of strings. Boost.Python has
434excellent support for things like that:
435
436    list names_wrapper()
437    {
438        list result;
439        // call original function
440        vector<string> v = names();
441        // put all the strings inside the python list
442        vector<string>::iterator it;
443        for (it = v.begin(); it != v.end(); ++it){
444            result.append(*it);   
445        }
446        return result;
447    }
448   
449    BOOST_PYTHON_MODULE(test)
450    {
451        def("names", &names_wrapper);
452    }
453
454Nice heh? Pyste supports this mechanism too. You declare the [^names_wrapper]
455function in a header named "[^test_wrappers.h]" and in the interface file:
456
457    Include("test_wrappers.h")
458    names = Function("names", "test.h")
459    set_wrapper(names, "names_wrapper")
460
461You can optionally declare the function in the interface file itself:
462
463    names_wrapper = Wrapper("names_wrapper",
464    """
465    list names_wrapper()
466    {
467        // code to call name() and convert the vector to a list...
468    }
469    """)
470    names = Function("names", "test.h")
471    set_wrapper(names, names_wrapper)
472
473The same mechanism can be used with member functions too. Just remember that
474the first parameter of wrappers for member functions is a pointer to the
475class, as in:
476
477    struct C
478    {
479        std::vector<std::string> names();
480    }
481
482    list names_wrapper(C* c)
483    {
484        // same as before, calling c->names() and converting result to a list
485    }
486
487And then in the interface file:
488
489    C = Class("C", "test.h")
490    set_wrapper(C.names, "names_wrapper")
491
492[blurb
493[$theme/note.gif]Even though Boost.Python accepts either a pointer or a
494reference to the class in wrappers for member functions as the first parameter,
495Pyste expects them to be a [*pointer]. Doing otherwise will prevent your
496code to compile when you set a wrapper for a virtual member function.
497]
498
499[page:1 Exporting An Entire Header]
500
501Pyste also supports a mechanism to export all declarations found in a header
502file. Suppose again our file, [^hello.h]:
503
504    struct World
505    {
506        World(std::string msg): msg(msg) {}
507        void set(std::string msg) { this->msg = msg; }
508        std::string greet() { return msg; }
509        std::string msg;
510    };
511
512    enum choice { red, blue };
513   
514    void show(choice c) { std::cout << "value: " << (int)c << std::endl; }
515
516You can just use the [^AllFromHeader] construct:
517
518    hello = AllFromHeader("hello.h")
519
520this will export all the declarations found in [^hello.h], which is equivalent
521to write:
522
523    Class("World", "hello.h")
524    Enum("choice", "hello.h")
525    Function("show", "hello.h")
526
527Note that you can still use the functions [^rename], [^set_policy], [^exclude], etc. Just access
528the members of the header object like this:
529
530    rename(hello.World.greet, "Greet")
531    exclude(hello.World.set, "Set")
532
533[blurb   
534[$theme/note.gif] [*AllFromHeader is broken] in some cases. Until it is fixed,
535use at you own risk.
536]
537
538
539[page:1 Smart Pointers]
540
541Pyste for now has manual support for smart pointers. Suppose:
542
543    struct C
544    {
545        int value;
546    };
547
548    boost::shared_ptr<C> newC(int value)
549    {
550        boost::shared_ptr<C> c( new C() );
551        c->value = value;
552        return c;
553    }
554
555    void printC(boost::shared_ptr<C> c)
556    {
557        std::cout << c->value << std::endl;
558    }
559
560To make [^newC] and [^printC] work correctly, you have to tell Pyste that a
561convertor for [^boost::shared_ptr<C>] is needed.
562
563    C = Class('C', 'C.h')
564    use_shared_ptr(C)
565    Function('newC', 'C.h')
566    Function('printC', 'C.h')
567
568For [^std::auto_ptr]'s, use the function [^use_auto_ptr].
569
570This system is temporary, and in the future the converters will automatically be
571exported if needed, without the need to tell Pyste about them explicitly.
572
573[h2 Holders]
574
575If only the converter for the smart pointers is not enough and you need to
576specify the smart pointer as the holder for a class, use the functions
577[^hold_with_shared_ptr] and [^hold_with_auto_ptr]:
578
579    C = Class('C', 'C.h')
580    hold_with_shared_ptr(C)
581    Function('newC', 'C.h')
582    Function('printC', 'C.h')
583
584[page:1 Global Variables]
585
586To export global variables, use the [^Var] construct:
587
588    Var("myglobal", "foo.h")
589
590Beware of non-const global variables: changes in Python won't reflect in C++!
591If you really must change them in Python, you will have to write some accessor
592functions, and export those.
593
594
595[page:1 Adding New Methods]
596
597Suppose that you want to add a function to a class, turning it into a member
598function:
599
600    struct World
601    {
602        void set(std::string msg) { this->msg = msg; }
603        std::string msg;
604    };
605
606    std::string greet(World& w)
607    {
608        return w.msg;
609    }
610
611Here, we want to make [^greet] work as a member function of the class [^World]. We do
612that using the [^add_method] construct:
613
614    W = Class("World", "hello.h")
615    add_method(W, "greet")
616
617Notice also that then you can rename it, set its policy, just like a regular
618member function:
619
620    rename(W.greet, 'Greet')
621
622Now from Python:
623
624    >>> import hello
625    >>> w = hello.World()
626    >>> w.set('Ni')
627    >>> w.greet()
628    'Ni'
629    >>> print 'Oh no! The knights who say Ni!'
630    Oh no! The knights who say Ni!
631
632
633[page:1 Inserting Code]
634
635You can insert arbitrary code in the generated cpps, just use the functions
636[^declaration_code] and [^module_code]. This will insert the given string in the
637respective sections. Example:
638
639    # file A.pyste
640    Class("A", "A.h")
641    declaration_code("/* declaration_code() comes here */\n")
642    module_code("/* module_code() comes here */\n")
643
644Will generate:
645
646    // Includes ====================================================================
647    #include <boost/python.hpp>
648
649    // Using =======================================================================
650    using namespace boost::python;
651
652    // Declarations ================================================================
653
654    /* declaration_code() comes here */
655
656    // Module ======================================================================
657    BOOST_PYTHON_MODULE(A)
658    {
659        class_< A >("A", init<  >())
660            .def(init< const A& >())
661        ;
662
663    /* module_code() comes here */
664    }
Note: See TracBrowser for help on using the repository browser.