Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: downloads/boost_1_33_1/libs/python/pyste/doc/pyste.txt @ 13

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

added boost

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