Home
Using SWIG to Control, Prototype, and Debug C Programs with Python
Contents
1. 250 functions and variables e Used on CM 5 T3D Workstations e SWIG is hidden in the Makefile and is completely transparent to the users e Simplicity of approach is particularly attractive in research applications SWIG 18 4th International Python Conference Building Python Modules and Classes e Can build Python modules out of C C libraries Example MATLAB OpenGL etc e Can encapsulate C classes with a little work module tree import tree include tree h class Tree def _ init self self ptr new Tree class Tree def del self public delete Tree self ptr Tree def insert self key val Tree Tree insert self ptr key val void insert char key char val def search self key char search char key v Tree_search self ptr key return v void remove char key def remove self key Tree remove self ptr key e Combining various modules usually leads to interesting applications SWIG 4th International Python Conference SWIG Prototyping and Debugging SWIG works well if you want to interact with and debug C C code Example OpenGL odule opengl nclude glu i Most of the GLU library nclude aux i Most of the GL aux library nclude help i A few functions added to help out de JE AP AP oP AP m include gl i All of the OpenGL library i 1 1 Each include file is just an edited copy of various GL header files Total d
2. Control language Cool things like lists associative arrays modules etc Interpreted Good extension language Rapid prototyping Debuggin User interfaces tkinter e Use the best features of each language SWIG 5 4th International Python Conference Extending Python Suppose you wanted to add the getenv function to Python A Python wrapper function e Need to write special l l wrapper functions static PyObject wrap_getenv PyObject self PyObject args e Fortunately it s usually not too difficult char result char arg0 But imagine doing pe RE eaters this for 200 functions wenk neten tands return Py BuildValue s result Tedious and error prone Procedure is about the same for most other scripting languages some are easier than others SWIG 6 4th International Python Conference SWIG Overview Interface file with ANSI C C e Generic YACC Parser e Target languages are C classes Code Doc Generator Generator e Easy to extend well mostly e Produces a C C Python HTML fil Tcl LaTeX source file as output Perla ASCII er Guile iii SWIG 8 4th International Python Conference A Simple Example example c example i SWIG Interface File smodule example int fact int n if n lt 1 return 1 Insert headers here else return n fact n 1 5 extern int fact int unix swig python example i unix gcc c example c example
3. language e Use of special syntax or formatting e Difficult to use SWIG e Use ANSI C C specifications independent of target language e Try to keep it simple yet flexible e hate religious wars SWIG 7 4th International Python Conference SWIG Random Thoughts SWIG vs hand written modules e SWIG was not really designed to be a generic module builder Performance concerns e You don t use interpreted languages if you want performance e 2 Language Module gt Write critical stuff in C C Security and Reliability e Type checker eliminates alot of problems e Can still forge bogus pointer values e C is always a little risky pointer casting problems for instance Coding Methodology e When used during code development SWIG encourages modularity e Usually results in more reliable and flexible code Why all of the Effort want to have a useful and reliable tool 25 4th International Python Conference Building a SWIG Extension e Need to supply a new language class about a dozen functions e Write a main program like this include lt swig h gt include lt my_python h gt int main int argc char argv PYTHON Ls l new PYTHON SWIG_main argc argv 1 Documentation 0 return 0 e Recompile unix gt g my_python C main C lswig o myswig e Unfortunately the code in my_python C is pretty ugly working on it SWIG 4th International Python
4. wrap c I usr local include Py unix ld shared example o example wrap o o example so unix pythonl 3 Python1 3 Apr 12 1996 GCC 2 5 8 Copyright 1991 1995 Stichting Mathematisch Centrum Amsterdam gt gt gt from example import gt gt gt n fact 6 gt gt gt print n 720 gt gt gt SWIG 9 4th International Python Conference SWIG SWIG Datatypes Built in types int short long char float double void integers can also be signed or unsigned Derived types e Pointers to built in types e Pointers to structures e Pointers to objects e Well almost any kind of pointer actually In fact all derived types are pointers in SWIG but more on that in a minute Can remap types using typedef The bottom line e Almost all C C datatypes can be used e No pointers to functions unless hidden via typedef e Arrays a little weird too 10 4th International Python Conference Adding Functions e SWIG uses ANSI C C prototypes int foo int a int b extern void print_data double unsigned int f1 void 2 extern int strcmp const char const char struct tm localtime long t double new_matrix int n int m Node xget_node char int Foo bar e All built in types and derived types allowed e No type information needed for complex datatypes ie Node or struct tm e Usually pretty easy to use header files e Parser throws out some clutter inlin
5. Conference
6. Using SWIG to Control Prototype and Debug C Programs with Python Dave Beazley Department of Computer Science University of Utah Salt Lake City Utah 84112 beazley cs utah edu June 5 1996 SWIG 1 4th International Python Conference Topics e What is SWIG e Extending Python e A Tour of SWIG e Applications e Limitations e Work in progress and future directions SWIG 2 4th International Python Conference SWIG Simplified Wrapper and Interface Generator SWIG Compiler that takes ANSI C C declarations and produces bindings to interpreted languages Supports almost all C C datatypes Binds functions variables and constants C classes including some inheritance Run time type checking Supports modules and multiple files Automatic documentation generation Currently supports Python Tcl Perl4 Perl5 Guile3 Extensible 3 Ath International Python Conference Where am I Coming From Compilers Physics l l Debugging Numerical Rapid Prototyping K Analysis x Dave s Scripting lt ML Language 100 Gbytes K of Data LN PM Pe ORS SWIG Prototype Dave s Attitude Python Perl Problem Tcl Tk Guile Sa Ease of Use nn SWIG __ Documentation ze Physicists SWIG Ath International Python Conference The Two Language Model e Two languages are better than one e C C Performance Hard core number crunching Portability Complicated stuff e Python
7. Whatever else comes up 24 4th International Python Conference SWIG Acknowledgments All of the current users who have provided feedback bug reports and ideas The first users Kurtis Bleeker Tim Germann Brad Holian Peter Lomdahl John Schmidt Peter Pike Sloan Shujia Zhou John Buckman non unix platforms and lots of good ideas Patrick Tullmann automatic documentation generation The Scientific Computing and Imaging Group Oh and these agencies paid some of my salary and provided machines DOE NSF NIH 27 4th International Python Conference Advertisement The SWIG source code and user manual are available via anonymous FTP ftp cs utah edu pub beazley SWIG The SWIG homepage http www cs utah edu beazley SWIG The SWIG mailing list swig cs utah edu SWIG 28 4th International Python Conference Conclusions e SWIG Eliminates alot of the grungy details of integrating C C with Python e Current system supports a reasonable subset of C and C e Two language model is where it s at e Many users like the easy of use and straightforward approach e developed SWIG for myself and I find myself using it almost all of the time but I m probably biased SWIG 26 4th International Python Conference Automatic Wrapper Generation e Most languages have tools for automatically generating wrapper code ex ILU Modulator Object Tcl XS etc e Most tools are specific to a single
8. e code etc SWIG 11 4th International Python Conference Linking to C Variables and Constants SWIG Access global variables by declaring them double My variable extern int flag Node root In python this creates functions such as the following double My variable get double My variable set double newvalue Create constants with define enum or const define MODE 1 enum colors red blue green yellow brown const int FLAGS 0x04000020 Constant expressions allowed define STATUS 0x20 0x1 Ox1000 const double PI 4 PI 4 12 4th International Python Conference Pointers e All derived types in SWIG are pointers e Encoded as strings with type information Example _1008e124 Vector_p Hmmm perhaps a carry over from Tcl e Checked at run time for validity gt gt gt n new Node gt gt gt v new Vector 3 5 10 gt gt gt d dot v n Traceback innermost last File line 1 in TypeError Type error in argument 2 of dot Expected Vector p gt gt gt e Type checker is savvy to typedef and C e Prevents crashes due to stupid mistakes SWIG 13 4th International Python Conference SWIG and C S module list include list h 5 class List public List List int search char item void insert char item void remove char item char get int n int length static void print List 1 e C code politely trans
9. evelopment time 20 minutes e 708 Constants e 426 Functions e gt 8000 lines of wrapper code 20 Ath International Python Conference from open def myini OpenGL Example gl import te 8 light_ambient newfv4 0 0 0 0 Oy Lee Je light diffuse newfv4 1 0 1 0 0 1 0 light_specular newfv4 1 0 1 0 1 0 1 0 light position newfv4 0 0 1 0 0 0 glLightfv GL_LIGHTO GL AMBIENT light ambient glLightfv GL LIGHTO GL DIFFUSE light diffuse glLightfv GL LIGHTO GL SPECULAR light specular glLightfv GL_LIGHTO GL POSITION light position glEnable GL LIGHTING glEnable GL LIGHTO glDepthFunc GL LESS glEnable GL DEPTH_ TEST def display glClear GL_ COLOR BUFFER BIT GL DEPTH BUFFER BIT glPushMatrix glRotatef 20 0 1 0 0 0 0 0 glPushMatrix glTranslatef 0 75 0 5 0 0 glRotatef 90 0 1 0 0 0 0 0 auxSolidTorus 0 275 0 85 glPopMatrix glPus hMatrix glTranslatef 0 75 0 5 0 0 glRot auxso atef 270 0 1 0 0 lidCone 1 0 2 0 glPopMatrix glPus hMatrix glTranslatef 0 75 0 0 auxSolidSphere 1 0 glPopMatrix glPopMatrix glFlush SWIG 0 0 0 1 0 7 21 Ath International Python Conference Curre
10. lated into C e C functions are then wrapped e Works independently of the target language e Can be fully customized work in progress SWIG List new_List void return new List void delete List List 1 delete 1 List search List 1 char item return 1 gt search item List length get List 1 return 1 gt length List length set List 1 int value return l gt length value void List print List 1 List print 1 4th International Python Conference SWIG SWIG and C cont Inheritance e SWIG supports single public inheritance e Virtual functions okay Use of C references usually works Limitations No operator overloading No templates No multiple inheritance No function overloading but you can rename things List Sname ListItem List char item Thoughts e C isa complicated beast Probably pretty hard to support all of it I ve tried to work with a reasonable subset e Wasn t my intent to write a full C compiler 15 4th International Python Conference SWIG Multiple Files and Modules Interfaces can be built from multiple files and libraries smodule package 5 include 5 Sinclude Sinclude Sinclude Sinclude Sinclude Sinclude package h geometry i file i graphics i network 1 integration i mesh i Module system makes it very easy to reuse code in other packages SWIG comes with a
11. library of stuff Code reuse that works maybe 16 4th International Python Conference Documentation System Documentation is generated automatically from comments title My Interface smodule package include package h 5 S8ect ion Initialization void init itializes izes the system and initiation ritual the system spawns an section Graphics void LoadMatrix Matrix m Loads viewing transformation matrix void ClearBuffer int color Clear the frame buffer Ssection Network int open_socket char host int port Open up a connection with the server void disconnect int fd Close connection SWIG 17 My Interface Ls Initialization void void package init Initializes the syst package haze Initializes the system and spawns an initiation ritual Graphics package LoadMat rix m Loads viewing transformation matrix package ClearBuffer color Clear the frame buffer Network package open_socket host port Open up a connection with the server package disconnect fd Close connection Ath International Python Conference Controlling C Programs e SWIG requires virtually no modification to C code e Easy to use with existing applications e Currently used at Los Alamos with the SPaSM Molecular Dynamics code
12. nt Limitations e Lack of variable linking in Python Ex double MyVariable gt MyVariable_get MyVariable_set e Representing pointers as strings is a little weird But you often don t notice e Handling of C classes not complete Often have to write a Python wrapper class afterwards e Pointer model is sometimes confusing e No exception model e Numerical representation problems particularly unsigned integers and longs e C parsing need say more SWIG 23 4th International Python Conference A Few Projects Using SWIG e Materials Science Simulations Los Alamos SWIG used for nearly a year System has worked flawlessly e Defibrillation research Univ of Utah Being used to glue together simulation mesh generation and visualization code using Tcl Tk e Synthetic workload generation Univ of Utah e OpenGL widget Peter Pike Sloan Univ of Utah e and many other projects underway SWIG 22 Ath International Python Conference SWIG Future Directions Release of 1 0 Final someday Continued improvement to Python implementation e Perhaps a new pointer representation Better method for linking with variables e Improved C support e An exception model Integration with Numerical Python Python for parallel machines A little unrelated but ld like it Support for new target languages as appropriate e Java well maybe e ILU e iTcl Support for non Unix platforms in progress
Download Pdf Manuals
Related Search
Related Contents
Monitor - Newegg.com Belinea 10 30 50 - Quant Electronic LifeSize Recertification Fee - UVC Video Center C-700 Ultra Zoom 取扱説明書 Istruzioni d`uso Apparecchiatura SG Leica V-LUX 40 Instruction Manual Samsung HMX-U20BP Инструкция по использованию University of Southern California School of Pharmacy Medication Anti Stress : La Sieste Copyright © All rights reserved.
Failed to retrieve file