merged in Vitja's tab removals
[cython.git] / Doc / overview.html
1 <!DOCTYPE doctype PUBLIC "-//w3c//dtd html 4.0 transitional//en">
2 <html><head>
3              
4   <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
5
6              
7   <meta name="GENERATOR" content="Mozilla/4.61 (Macintosh; I; PPC) [Netscape]">
8   <title>Cython Language Overview</title>
9 </head>
10 <body>
11      
12 <h1>   <hr width="100%">Overview of the Cython Language&nbsp;  <hr width="100%"></h1>
13
14    This document informally describes the extensions to the Python language 
15  made by Cython. Some day there will be a reference manual covering everything 
16  in more detail. <br>
17
18   &nbsp;  
19 <h2> Contents</h2>
20
21      
22 <ul>
23
24    <li> <a href="#Basics">Basics</a></li>
25            <ul>
26    <li> <a href="#PyFuncsVsCFuncs">Python functions vs. C functions</a></li>
27     <li> <a href="#PyObjParams">Python objects as parameters</a></li>
28     <li> <a href="#CVarAndTypeDecls">C variable and type definitions</a></li><li><a href="#AutomaticTypeConversions">Automatic type conversions</a></li>
29     <ul>
30       <li><a href="#PyToCStringCaveats">Caveats when using a Python string in a C context</a></li>
31     </ul>
32
33     <li> <a href="#ScopeRules">Scope rules</a></li>
34     <li> <a href="#StatsAndExprs">Statements and expressions</a></li>
35                  <ul>
36    <li> <a href="#ExprSyntaxDifferences">Differences between C and Cython
37 expressions<br>
38 </a></li>
39     <li> <a href="#ForFromLoop">Integer for-loops</a></li>
40                 </ul>
41     <li> <a href="#ExceptionValues">Error return values</a></li>
42                  <ul>
43    <li> <a href="#CheckingReturnValues">Checking return values of non-Cython
44  functions</a></li>
45                 </ul>
46     <li> <a href="#IncludeStatement">The <tt>include</tt> statement</a></li>
47           </ul>
48     <li> <a href="#InterfacingWithExternal">Interfacing with External C Code</a></li>
49            <ul>
50    <li> <a href="#ExternDecls">External declarations</a></li>
51                  <ul>
52    <li> <a href="#ReferencingHeaders">Referencing C header files</a></li>
53     <li> <a href="#StructDeclStyles">Styles of struct/union/enum declaration</a></li>
54     <li> <a href="#AccessingAPI">Accessing Python/C API routines</a></li>
55     <li> <a href="#CNameSpecs">Resolving naming conflicts - C name specifications</a></li>
56                 </ul>
57     <li> <a href="#PublicDecls">Public declarations</a></li>
58           </ul>
59     <li> <a href="extension_types.html">Extension Types</a> <font color="#006600">(Section revised in 0.9)</font></li>
60     <li> <a href="sharing.html">Sharing Declarations Between Cython Modules</a>
61      <font color="#006600">(NEW in 0.8)</font></li>
62     <li> <a href="#Limitations">Limitations</a></li>
63            <ul>
64    <li> <a href="#Unsupported">Unsupported Python features</a></li>
65     <li> <a href="#SemanticDifferences">Semantic differences between Python
66  and Cython</a></li>
67           </ul>
68     
69 </ul>
70
71      
72 <h2>   <hr width="100%"><a name="Basics"></a>Basics   
73 <hr width="100%"></h2>
74
75    This section describes the basic features of the Cython language. The facilities 
76  covered in this section allow you to create Python-callable functions that 
77  manipulate C data structures and convert between Python and C data types. 
78  Later sections will cover facilities for <a href="#InterfacingWithExternal">wrapping external C code</a>, <a href="extension_types.html">creating new Python types</a> and <a href="sharing.html">cooperation between Cython modules</a>.   
79 <h3> <a name="PyFuncsVsCFuncs"></a>Python functions vs. C functions</h3>
80
81    There are two kinds of function definition in Cython:   
82 <p><b>Python functions</b> are defined using the <b>def</b> statement, as
83  in Python. They take Python objects as parameters and return Python objects. 
84  </p>
85
86    
87 <p><b>C functions</b> are defined using the new <b>cdef</b> statement. They
88  take either Python objects or C values as parameters, and can return either
89  Python objects or C values. </p>
90
91    
92 <p>Within a Cython module, Python functions and C functions can call each other
93 freely, but only Python functions can be called from outside the module by
94 interpreted Python code. So, any functions that you want to "export" from
95  your Cython module must be declared as Python functions using <span style="font-weight: bold;">def</span>. </p>
96
97    
98 <p>Parameters of either type of function can be declared to have C data types,
99  using normal C declaration syntax. For example, </p>
100
101    
102 <blockquote>        <pre>def spam(int i, char *s):<br>&nbsp;&nbsp;&nbsp; ...</pre>
103            <pre>cdef int eggs(unsigned long l, float f):<br>&nbsp;&nbsp;&nbsp; ...</pre>
104    </blockquote>
105
106    When a parameter of a Python function is declared to have a C data type, 
107  it is passed in as a Python object and automatically converted to a C value, 
108  if possible. Automatic conversion is currently only possible for numeric 
109 types and string types; attempting to use any other type for the parameter 
110 of a Python function will result in a compile-time error.   
111 <p>C functions, on the other hand, can have parameters of any type, since 
112  they're passed in directly using a normal C function call. </p>
113
114    
115 <h3> <a name="PyObjParams"></a>Python objects as parameters and return values</h3>
116
117    If no type is specified for a parameter or return value, <i>it is assumed 
118  to be a Python object.</i> (Note that this is different from the C convention, 
119  where it would default to <tt>int</tt>.) For example, the following defines 
120  a C function that takes two Python objects as parameters and returns a Python
121  object:   
122 <blockquote>        <pre>cdef spamobjs(x, y):<br>&nbsp;&nbsp;&nbsp; ...</pre>
123    </blockquote>
124
125    Reference counting for these objects is performed automatically according 
126  to the standard Python/C API rules (i.e. borrowed references are taken as
127  parameters and a new reference is returned).   
128 <p>The name <b>object</b> can also be used to explicitly declare something 
129  as a Python object. This can be useful if the name being declared would otherwise
130 be taken as the name of a type, for example, </p>
131
132    
133 <blockquote>        <pre>cdef ftang(object int):<br>&nbsp;&nbsp;&nbsp; ...</pre>
134    </blockquote>
135
136    declares a parameter called <tt>int</tt> which is a Python object. You 
137 can also use <b>object </b>as the explicit return type of a function, e.g. 
138   
139 <blockquote>        <pre>cdef object ftang(object int):<br>&nbsp;&nbsp;&nbsp; ...</pre>
140    </blockquote>
141
142    In the interests of clarity, it is probably a good idea to always be explicit 
143  about <b>object </b>parameters in C functions.   
144 <h3> <a name="CVarAndTypeDecls"></a>C variable and type definitions</h3>
145
146    The <b>cdef</b> statement is also used to declare C variables, either
147 local  or module-level:   
148 <blockquote>        <pre>cdef int i, j, k<br>cdef float f, g[42], *h</pre>
149    </blockquote>
150
151    and C struct, union or enum types:   
152 <blockquote>        <pre>cdef struct Grail:<br>&nbsp;&nbsp;&nbsp; int age<br>&nbsp;&nbsp;&nbsp; float volume</pre>
153            <pre>cdef union Food:<br>&nbsp;&nbsp;&nbsp; char *spam<br>&nbsp;&nbsp;&nbsp; float *eggs</pre>
154            <pre>cdef enum CheeseType:<br>&nbsp;&nbsp;&nbsp; cheddar, edam,&nbsp;<br>&nbsp;&nbsp;&nbsp; camembert</pre>
155            <pre>cdef enum CheeseState:<br>&nbsp;&nbsp;&nbsp; hard = 1<br>&nbsp;&nbsp;&nbsp; soft = 2<br>&nbsp;&nbsp;&nbsp; runny = 3</pre>
156    </blockquote>
157
158    There is currently no special syntax for defining a constant, but you
159 can  use an anonymous enum declaration for this purpose, for example,   
160 <blockquote><tt>cdef enum:</tt> <br>
161     <tt>&nbsp;&nbsp;&nbsp; tons_of_spam = 3</tt></blockquote>
162
163    Note that the words <span style="font-family: monospace;">struct</span>, <span style="font-family: monospace;">union</span> and <span style="font-family: monospace;">enum</span> are used only when <i>defining</i> a type, not when referring to it. For example, to declare a variable pointing 
164  to a Grail you would write   
165 <blockquote>        <pre>cdef Grail *gp</pre>
166    </blockquote>
167
168    and <i>not</i>  
169 <blockquote>        <pre>cdef struct Grail *gp <font color="#ed181e"># WRONG</font></pre>
170    </blockquote>
171
172    There is also a <b>ctypedef</b> statement for giving names to types, e.g. 
173   
174 <blockquote>        <pre>ctypedef unsigned long ULong</pre>
175            <pre>ctypedef int *IntPtr<br></pre></blockquote>
176
177 <h3><a name="AutomaticTypeConversions"></a>Automatic type conversions</h3>
178
179 In most situations, automatic conversions will be performed for the
180 basic numeric and string types when a Python object is used in a
181 context requiring a C value, or vice versa. The following table
182 summarises the conversion possibilities.<br>
183
184 <br>
185
186 <table style="margin-left: auto; margin-right: auto; width: 10%; text-align: left;" border="1" cellpadding="4" cellspacing="0">
187
188   <tbody>
189     <tr>
190       <th style="vertical-align: top; width: 40%; white-space: nowrap;">C types<br>
191       </th>
192       <th style="vertical-align: top; width: 150px; white-space: nowrap;">From Python types<br>
193       </th>
194       <th style="vertical-align: top; width: 150px; white-space: nowrap;">To Python types<br>
195       </th>
196     </tr>
197     <tr>
198       <td colspan="1" rowspan="1" style="vertical-align: top; width: 40%; white-space: nowrap;">[unsigned] char<br>
199 [unsigned] short<br>
200       int, long</td>
201       <td colspan="1" rowspan="1" style="vertical-align: top; width: 150px; white-space: nowrap;">int, long<br>
202       </td>
203       <td colspan="1" rowspan="1" style="vertical-align: top; width: 150px; white-space: nowrap;">int<br>
204       </td>
205     </tr>
206     <tr>
207     </tr>
208
209     <tr>
210       <td colspan="1" rowspan="1" style="vertical-align: top; width: 40%; white-space: nowrap;">unsigned int<br>
211 unsigned long<br>
212       [unsigned] long long<br>
213
214       </td>
215       <td colspan="1" rowspan="1" style="vertical-align: top; white-space: nowrap;">int, long<br>
216       <br>
217
218       </td>
219       <td colspan="1" rowspan="1" style="vertical-align: top; white-space: nowrap;">long<br>
220       <br>
221
222       </td>
223     </tr>
224     <tr>
225       
226       
227       
228     </tr>
229     <tr>
230       <td style="vertical-align: top; width: 40%; white-space: nowrap;">float, double, long double<br>
231       </td>
232       <td style="vertical-align: top; width: 150px; white-space: nowrap;">int, long, float<br>
233       </td>
234       <td style="vertical-align: top; width: 150px; white-space: nowrap;">float<br>
235       </td>
236     </tr>
237     <tr>
238       <td style="vertical-align: top; width: 40%; white-space: nowrap;">char *<br>
239       </td>
240       <td style="vertical-align: top; width: 150px; white-space: nowrap;">str<span style="font-style: italic;"></span><br>
241       </td>
242       <td style="vertical-align: top; width: 150px; white-space: nowrap;">str<br>
243       </td>
244     </tr>
245   </tbody>
246 </table>
247
248 <br>
249
250 <h4><a name="PyToCStringCaveats"></a>Caveats when using a Python string in a C context</h4>
251
252 You need to be careful when using a Python string in a context expecting a <span style="font-family: monospace;">char *</span>.
253 In this situation, a pointer to the contents of the Python string is
254 used, which is only valid as long as the Python string exists. So you
255 need to make sure that a reference to the original Python string is
256 held for as long as the C string is needed. If you can't guarantee that
257 the Python string will live long enough, you will need to copy the C
258 string.<br>
259
260 <br>
261
262 Cython detects and prevents <span style="font-style: italic;">some</span> mistakes of this kind. For instance, if you attempt something like<br>
263
264 <pre style="margin-left: 40px;">cdef char *s<br>s = pystring1 + pystring2</pre>
265
266 then Cython will produce the error message "<span style="font-weight: bold;">Obtaining char * from temporary Python value</span>".
267 The reason is that concatenating the two Python strings produces a new
268 Python string object that is referenced only by a temporary internal
269 variable that Cython generates. As soon as the statement has finished,
270 the temporary variable will be decrefed and the Python string
271 deallocated, leaving <span style="font-family: monospace;">s</span> dangling. Since this code could not possibly work, Cython refuses to compile it.<br>
272
273 <br>
274
275 The solution is to assign the result of the concatenation to a Python variable, and then obtain the char * from that, i.e.<br>
276
277 <pre style="margin-left: 40px;">cdef char *s<br>p = pystring1 + pystring2<br>s = p<br></pre>
278
279 It is then your responsibility to hold the reference <span style="font-family: monospace;">p</span> for as long as necessary.<br>
280
281 <br>
282
283 Keep in mind that the rules used to detect such errors are only
284 heuristics. Sometimes Cython will complain unnecessarily, and sometimes
285 it will fail to detect a problem that exists. Ultimately, you need to
286 understand the issue and be careful what you do.<br>
287
288 <blockquote>
289    </blockquote>
290
291
292      
293 <h3> <a name="ScopeRules"></a>Scope rules</h3>
294
295    Cython determines whether a variable belongs to a local scope, the module 
296  scope, or the built-in scope <i>completely statically.</i> As with Python, 
297  assigning to a variable which is not otherwise declared implicitly declares 
298  it to be a Python variable residing in the scope where it is assigned. Unlike
299  Python, however, a name which is referred to but not declared or assigned
300  is assumed to reside in the <i>builtin scope, </i>not the module scope.
301 Names  added to the module dictionary at run time will not shadow such names.
302   
303 <p>You can use a <b>global</b> statement at the module level to explicitly 
304  declare a name to be a module-level name when there would otherwise not be
305 any indication of this, for example, </p>
306
307    
308 <blockquote><tt>global __name__</tt> <br>
309     <tt>print __name__</tt></blockquote>
310
311    Without the <b>global</b> statement, the above would print the name of 
312 the builtins module.<br>
313
314   <br>
315
316   Note: A consequence of these rules is that the module-level scope behaves
317  the same way as a Python local scope if you refer to a variable before assigning
318  to it. In particular, tricks such as the following will <i>not</i> work
319 in  Cython:<br>
320
321    
322 <blockquote>        <pre>try:<br>&nbsp; x = True<br>except NameError:<br>&nbsp; True = 1<br></pre>
323   </blockquote>
324
325   because, due to the assignment, the True will always be looked up in the
326  module-level scope. You would have to do something like this instead:<br>
327
328    
329 <blockquote>        <pre>import __builtin__<br>try:<br>  True = __builtin__.True<br>except AttributeError:<br>  True = 1<br></pre>
330   </blockquote>
331
332    
333 <hr width="100%">  
334 <h3> <a name="StatsAndExprs"></a>Statements and expressions</h3>
335
336    Control structures and expressions follow Python syntax for the most part. 
337  When applied to Python objects, they have the same semantics as in Python 
338  (unless otherwise noted). Most of the Python operators can also be applied 
339  to C values, with the obvious semantics.   
340 <p>If Python objects and C values are mixed in an expression, conversions 
341  are performed automatically between Python objects and C numeric or string 
342  types. </p>
343
344    
345 <p>Reference counts are maintained automatically for all Python objects, and
346 all Python operations are automatically checked for errors, with appropriate 
347  action taken. </p>
348
349    
350 <h4> <a name="ExprSyntaxDifferences"></a>Differences between C and Cython
351 expressions</h4>
352 There
353 are some differences in syntax and semantics between C expressions and
354 Cython expressions, particularly in the area of C constructs which have
355 no direct equivalent in Python.<br>
356
357 <ul>
358 <li>An integer literal without an <span style="font-family: monospace; font-weight: bold;">L</span> suffix is treated as a C constant, and will be truncated to whatever size your C compiler thinks appropriate. With an <span style="font-family: monospace; font-weight: bold;">L</span> suffix, it will be converted to Python long integer (even if it would be small enough to fit into a C int).<br>
359     <br>
360   </li>
361 <li> There is no <b><tt>-&gt;</tt></b> operator in Cython. Instead of <tt>p-&gt;x</tt>, 
362  use <tt>p.x</tt></li>
363     
364   &nbsp; <li> There is no <b><tt>*</tt></b> operator in Cython. Instead of 
365     <tt>*p</tt>,  use <tt>p[0]</tt></li>
366     
367   &nbsp; <li> There is an <b><tt>&amp;</tt></b> operator, with the same semantics
368  as in C.</li>
369     
370   &nbsp; <li> The null C pointer is called <b><tt>NULL</tt></b>, not 0 (and
371      <tt>NULL</tt> is a reserved word).</li>
372     
373   &nbsp; <li> Character literals are written with a <b>c</b> prefix, for
374 example:</li>
375            <ul>
376                 <pre>c'X'</pre>
377           </ul>
378     <li> Type casts are written <b><tt>&lt;type&gt;value</tt></b> , for example:</li>
379            <ul>
380                 <pre>cdef char *p, float *q<br>p = &lt;char*&gt;q</pre>
381           </ul>
382    <i><b>Warning</b>: Don't attempt to use a typecast to convert between
383 Python  and C data types -- it won't do the right thing. Leave Cython to perform 
384 the conversion automatically.</i>  
385 </ul>
386
387      
388 <h4> <a name="ForFromLoop"></a>Integer for-loops</h4>
389
390    You should be aware that a for-loop such as   
391 <blockquote><tt>for i in range(n):</tt> <br>
392     <tt>&nbsp;&nbsp;&nbsp; ...</tt></blockquote>
393
394    won't be very fast, even if <tt>i</tt> and <tt>n</tt> are declared as
395 C integers, because <tt>range</tt> is a Python function. For iterating over 
396 ranges of integers, Cython has another form of for-loop:   
397 <blockquote><tt>for i from 0 &lt;= i &lt; n:</tt> <br>
398     <tt>&nbsp;&nbsp;&nbsp; ...</tt></blockquote>
399
400    If the loop variable and the lower and upper bounds are all C integers, 
401 this form of loop will be much faster, because Cython will translate it into 
402 pure C code.   
403 <p>Some things to note about the <tt>for-from</tt> loop: </p>
404
405    
406 <ul>
407
408    <li> The target expression must be a variable name.</li>
409     <li> The name between the lower and upper bounds must be the same as
410 the  target name.</li>
411     <li> The direction of iteration is determined by the relations. If they
412  are both from the set {<tt>&lt;</tt>, <tt>&lt;=</tt>} then it is upwards;
413  if they are both from the set {<tt>&gt;</tt>, <tt>&gt;=</tt>} then it is
414 downwards. (Any other combination is disallowed.)</li>
415     
416 </ul>
417
418    Like other Python looping statements, <tt>break</tt> and <tt>continue</tt> may be used in the body, and the loop may have an <tt>else</tt> clause. 
419  
420 <h2>   <hr width="100%"></h2>
421
422      
423 <h3> <a name="ExceptionValues"></a>Error return values</h3>
424
425    If you don't do anything special, a function declared with <b>cdef</b> that does not return a Python object has no way of reporting Python exceptions 
426  to its caller. If an exception is detected in such a function, a warning 
427 message is printed and the exception is ignored.   
428 <p>If you want a C function that does not return a Python object to be able
429  to propagate exceptions to its caller, you need to declare an <b>exception 
430  value</b> for it. Here is an example: </p>
431
432    
433 <blockquote><tt>cdef int spam() except -1:</tt> <br>
434     <tt>&nbsp;&nbsp;&nbsp; ...</tt></blockquote>
435
436    With this declaration, whenever an exception occurs inside <tt>spam</tt>, 
437  it will immediately return with the value <tt>-1</tt>. Furthermore, whenever 
438  a call to <tt>spam</tt> returns <tt>-1</tt>, an exception will be assumed 
439  to have occurred and will be propagated.   
440 <p>When you declare an exception value for a function, you should never explicitly
441  return that value. If all possible return values are legal and you can't
442 reserve one entirely for signalling errors, you can use an alternative form
443 of exception value declaration: </p>
444
445    
446 <blockquote><tt>cdef int spam() except? -1:</tt> <br>
447     <tt>&nbsp;&nbsp;&nbsp; ...</tt></blockquote>
448
449    The "?" indicates that the value <tt>-1</tt> only indicates a <i>possible</i> error. In this case, Cython generates a call to <tt>PyErr_Occurred</tt>if the
450 exception value is returned, to make sure it really is an error.   
451 <p>There is also a third form of exception value declaration: </p>
452
453    
454 <blockquote><tt>cdef int spam() except *:</tt> <br>
455     <tt>&nbsp;&nbsp;&nbsp; ...</tt></blockquote>
456
457    This form causes Cython to generate a call to <tt>PyErr_Occurred</tt> after 
458  <i>every</i> call to spam, regardless of what value it returns. If you have
459  a function returning <tt>void</tt> that needs to propagate errors, you will
460  have to use this form, since there isn't any return value to test.   
461 <p>Some things to note: </p>
462
463    
464 <ul>
465
466    <li> Currently, exception values can only declared for functions returning
467  an integer, float or pointer type, and the value must be a <i>literal</i>, 
468  not an expression (although it can be negative). The only possible pointer 
469  exception value is <tt>NULL</tt>. Void functions can only use the <tt>except 
470  *</tt> form.</li>
471     <br>
472   &nbsp; <li> The exception value specification is part of the signature
473 of  the function. If you're passing a pointer to a function as a parameter
474 or  assigning it to a variable, the declared type of the parameter or variable
475  must have the same exception value specification (or lack thereof). Here
476 is an example of a pointer-to-function declaration with an exception value:</li>
477            <ul>
478                 <pre><tt>int (*grail)(int, char *) except -1</tt></pre>
479           </ul>
480     <li> You don't need to (and shouldn't) declare exception values for functions 
481  which return Python objects. Remember that a function with no declared return
482  type implicitly returns a Python object.</li>
483     
484 </ul>
485
486      
487 <h4> <a name="CheckingReturnValues"></a>Checking return values of non-Cython 
488  functions</h4>
489
490    It's important to understand that the <tt>except</tt> clause does <i>not</i> cause an error to be <i>raised</i> when the specified value is returned. For
491 example, you can't write something like   
492 <blockquote>        <pre>cdef extern FILE *fopen(char *filename, char *mode) except NULL <font color="#ed181e"># WRONG!</font></pre>
493    </blockquote>
494
495    and expect an exception to be automatically raised if a call to fopen
496 returns  NULL. The except clause doesn't work that way; its only purpose
497 is for <i>propagating</i> exceptions that have already been raised, either
498 by a Cython function or a  C function that calls Python/C API routines. To
499 get an exception from a non-Python-aware  function such as fopen, you will
500 have to check the return value and raise  it yourself, for example,   
501 <blockquote>        <pre>cdef FILE *p<br>p = fopen("spam.txt", "r")<br>if p == NULL:<br>&nbsp;&nbsp;&nbsp; raise SpamError("Couldn't open the spam file")</pre>
502    </blockquote>
503
504      
505 <h4>   <hr width="100%"></h4>
506
507      
508 <h4> <a name="IncludeStatement"></a>The <tt>include</tt> statement</h4>
509
510    For convenience, a large Cython module can be split up into a number of 
511 files which are put together using the <b>include</b> statement, for example 
512   
513 <blockquote>        <pre>include "spamstuff.pxi"</pre>
514    </blockquote>
515
516    The contents of the named file are textually included at that point. The 
517  included file can contain any complete top-level Cython statements, including 
518  other <b>include</b> statements. The <b>include</b> statement itself can 
519 only appear at the top level of a file.   
520 <p>The <b>include</b> statement can also be used in conjunction with <a href="#PublicDecls"><b>public</b> declarations</a> to make C functions and
521  variables defined in one Cython module accessible to another. However, note
522  that some of these uses have been superseded by the facilities described
523 in <a href="sharing.html">Sharing Declarations Between Cython Modules</a>,
524 and it is expected that use of the <b>include</b> statement for this purpose
525 will be phased out altogether in future versions. </p>
526
527    
528 <h2>   <hr width="100%"><a name="InterfacingWithExternal"></a>Interfacing with External
529  C Code   
530 <hr width="100%"></h2>
531
532    One of the main uses of Cython is wrapping existing libraries of C code. 
533 This is achieved by using <a href="#ExternDecls">external declarations</a> to declare the C functions and variables from the library that you want to
534  use.   
535 <p>You can also use <a href="#PublicDecls">public declarations</a> to make 
536  C functions and variables defined in a Cython module available to external 
537  C code. The need for this is expected to be less frequent, but you might 
538 want to do it, for example, if you are embedding Python in another application 
539  as a scripting language. Just as a Cython module can be used as a bridge to
540 allow Python code to call C code, it can also be used to allow C code to
541 call Python code. </p>
542
543    
544 <h3> <a name="ExternDecls"></a>External declarations</h3>
545
546    By default, C functions and variables declared at the module level are 
547 local to the module (i.e. they have the C <b>static</b> storage class). They 
548 can also be declared <b>extern</b> to specify that they are defined elsewhere,
549  for example:   
550 <blockquote>        <pre>cdef extern int spam_counter</pre>
551            <pre>cdef extern void order_spam(int tons)</pre>
552    </blockquote>
553
554      
555 <blockquote>         </blockquote>
556
557      
558 <h4> <a name="ReferencingHeaders"></a>Referencing C header files</h4>
559
560    When you use an extern definition on its own as in the examples above, 
561 Cython includes a declaration for it in the generated C file. This can cause 
562 problems if the declaration doesn't exactly match the declaration that will 
563 be seen by other C code. If you're wrapping an existing C library, for example, 
564 it's important that the generated C code is compiled with exactly the same 
565 declarations as the rest of the library.   
566 <p>To achieve this, you can tell Cython that the declarations are to be found
567  in a C header file, like this: </p>
568
569    
570 <blockquote>        <pre>cdef extern from "spam.h":</pre>
571            <pre>&nbsp;&nbsp;&nbsp; int spam_counter</pre>
572            <pre>&nbsp;&nbsp;&nbsp; void order_spam(int tons)</pre>
573    </blockquote>
574
575    The <b>cdef extern from</b> clause does three things:   
576 <ol>
577
578    <li> It directs Cython to place a <b>#include</b> statement for the named
579  header file in the generated C code.<br>
580    </li>
581   &nbsp; <li> It prevents Cython from generating any C code for the declarations
582  found in the associated block.<br>
583    </li>
584   &nbsp; <li> It treats all declarations within the block as though they
585 started  with <b>cdef extern</b>.</li>
586     
587 </ol>
588
589    It's important to understand that Cython does <i>not</i> itself read the 
590 C header file, so you still need to provide Cython versions of any declarations 
591  from it that you use. However, the Cython declarations don't always have to
592 exactly match the C ones, and in some cases they shouldn't or can't. In particular:
593   
594 <ol>
595
596    <li> Don't use <b>const</b>. Cython doesn't know anything about const,
597 so  just leave it out. Most of the time this shouldn't cause any problem,
598 although  on rare occasions you might have to use a cast.<sup><a href="#Footnote1"> 1</a></sup><br>
599    </li>
600   &nbsp; <li> Leave out any platform-specific extensions to C declarations
601  such as <b>__declspec()</b>.<br>
602    </li>
603   &nbsp; <li> If the header file declares a big struct and you only want
604 to  use a few members, you only need to declare the members you're interested 
605 in. Leaving the rest out doesn't do any harm, because the C compiler will 
606 use the full definition from the header file.<br>
607      <br>
608  In some cases, you might not need <i>any</i> of the struct's members, in
609 which case you can just put <tt>pass</tt> in the body of the struct declaration,
610 e.g.<br>
611      <br>
612      <tt>&nbsp; &nbsp; cdef extern from "foo.h":<br>
613  &nbsp; &nbsp; &nbsp; &nbsp; struct spam:<br>
614  &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; pass</tt><br>
615     <br>
616 Note that you can only do this inside a <b>cdef extern from</b> block; struct
617 declarations anywhere else must be non-empty.<br>
618     <br>
619    </li>
620     <li> If the header file uses typedef names such as <b>size_t </b>to refer 
621 to platform-dependent flavours of numeric types, you will need a corresponding 
622      <b>ctypedef</b> statement, but you don't need to match the type exactly,
623  just use something of the right general kind (int, float, etc). For example,</li>
624            <ol>
625                 <pre>ctypedef int size_t</pre>
626           </ol>
627    will work okay whatever the actual size of a size_t is (provided the header 
628  file defines it correctly). <br>
629   &nbsp; <li> If the header file uses macros to define constants, translate
630  them into a dummy <b>enum</b> declaration.<br>
631    </li>
632   &nbsp; <li> If the header file defines a function using a macro, declare
633  it as though it were an ordinary function, with appropriate argument and
634 result types.</li>
635     
636 </ol>
637
638    A few more tricks and tips:   
639 <ul>
640
641    <li> If you want to include a C header because it's needed by another
642 header,  but don't want to use any declarations from it, put <tt><font size="+1">pass</font></tt> in the extern-from block:</li>
643     
644 </ul>
645
646      
647 <ul>
648
649           <ul>
650       <tt>cdef extern from "spam.h":</tt> <br>
651       <tt>&nbsp;&nbsp;&nbsp; pass</tt>        </ul>
652     
653 </ul>
654
655      
656 <ul>
657
658    <li> If you want to include some external declarations, but don't want 
659 to specify a header file (because it's included by some other header that 
660 you've already included) you can put <tt>*</tt> in place of the header file 
661 name:</li>
662     
663 </ul>
664
665      
666 <blockquote>        <blockquote><tt>cdef extern from *:</tt> <br>
667       <tt>&nbsp;&nbsp;&nbsp; ...</tt></blockquote>
668    </blockquote>
669
670      
671 <h4> <a name="StructDeclStyles"></a>Styles of struct, union and enum declaration</h4>
672
673    There are two main ways that structs, unions and enums can be declared 
674 in C header files: using a tag name, or using a typedef. There are also some
675  variations based on various combinations of these.   
676 <p>It's important to make the Cython declarations match the style used in the
677 header file, so that Cython can emit the right sort of references to the type
678 in the code it generates. To make this possible, Cython provides two different
679 syntaxes for declaring a struct, union or enum type. The style introduced
680 above corresponds to the use of a tag name. To get the other style, you prefix
681 the declaration with <b>ctypedef</b>, as illustrated below. </p>
682
683    
684 <p>The following table shows the various possible styles that can be found 
685  in a header file, and the corresponding Cython declaration that you should 
686  put in the <b>cdef exern from </b>block. Struct declarations are used as 
687 an example; the same applies equally to union and enum declarations. </p>
688
689    
690 <p>Note that in all the cases below, you refer to the type in Cython code simply
691 as <tt><font size="+1">Foo</font></tt>, not <tt><font size="+1">struct Foo</font></tt>.
692  <br>
693   &nbsp;  <table cellpadding="5">
694    <tbody>
695       <tr bgcolor="#8cbc1c" valign="top">
696    <td bgcolor="#8cbc1c">&nbsp;</td>
697     <td bgcolor="#ff9933" nowrap="nowrap"><b>C code</b></td>
698     <td bgcolor="#66cccc" valign="top"><b>Possibilities for corresponding 
699 Cython  code</b></td>
700     <td bgcolor="#99cc33" valign="top"><b>Comments</b></td>
701    </tr>
702     <tr bgcolor="#8cbc1c" valign="top">
703    <td>1</td>
704     <td bgcolor="#ff9900"><tt>struct Foo {</tt> <br>
705         <tt>&nbsp; ...</tt> <br>
706         <tt>};</tt></td>
707     <td bgcolor="#66cccc"><tt>cdef struct Foo:</tt> <br>
708         <tt>&nbsp; ...</tt></td>
709     <td>Cython will refer to the type as <tt>struct Foo </tt>in the generated 
710  C code<tt>.</tt></td>
711    </tr>
712     <tr bgcolor="#8cbc1c" valign="top">
713    <td valign="top">2</td>
714     <td bgcolor="#ff9900" nowrap="nowrap"><tt>typedef struct {</tt> <br>
715         <tt>&nbsp; ...</tt> <br>
716         <tt>} Foo;</tt></td>
717     <td bgcolor="#66cccc" valign="top"><tt>ctypedef struct Foo:</tt> <br>
718         <tt>&nbsp; ...</tt></td>
719     <td valign="top">Cython will refer to the type simply as <tt>Foo</tt>
720 in  the generated C code.</td>
721    </tr>
722     <tr bgcolor="#8cbc1c" valign="top">
723    <td rowspan="2">3</td>
724     <td rowspan="2" bgcolor="#ff9900" nowrap="nowrap"><tt>typedef struct
725 foo  {</tt> <br>
726         <tt>&nbsp; ...</tt> <br>
727         <tt>} Foo;</tt></td>
728     <td bgcolor="#66cccc" nowrap="nowrap" valign="top"><tt>cdef struct foo:</tt>       <br>
729         <tt>&nbsp; ...</tt> <br>
730         <tt>ctypedef foo Foo #optional</tt></td>
731     <td rowspan="2" valign="top">If the C header uses both a tag and a typedef 
732  with <i>different</i> names, you can use either form of declaration in Cython
733  (although if you need to forward reference the type, you'll have to use
734 the  first form).</td>
735    </tr>
736     <tr>
737    <td bgcolor="#66cccc"><tt>ctypedef struct Foo:</tt> <br>
738         <tt>&nbsp; ...</tt></td>
739    </tr>
740     <tr bgcolor="#8cbc1c" valign="top">
741    <td>4</td>
742     <td bgcolor="#ff9900" nowrap="nowrap"><tt>typedef struct Foo {</tt> <br>
743         <tt>&nbsp; ...</tt> <br>
744         <tt>} Foo;</tt></td>
745     <td bgcolor="#66cccc" valign="top"><tt>cdef struct Foo:</tt> <br>
746         <tt>&nbsp; ...</tt></td>
747     <td>If the header uses the <i>same</i> name for the tag and the typedef, 
748  you won't be able to include a <b>ctypedef</b> for it -- but then, it's not
749 necessary.</td>
750    </tr>
751           </tbody>  </table>
752     </p>
753
754    
755 <h4> <a name="AccessingAPI"></a>Accessing Python/C API routines</h4>
756
757    One particular use of the <b>cdef extern from</b> statement is for gaining 
758  access to routines in the Python/C API. For example,   
759 <blockquote>        <pre>cdef extern from "Python.h":</pre>
760            <pre>&nbsp;&nbsp;&nbsp; object PyString_FromStringAndSize(char *s, int len)</pre>
761    </blockquote>
762
763    will allow you to create Python strings containing null bytes.   
764 <p> </p>
765
766    
767 <hr width="100%">  
768 <h3> <a name="CNameSpecs"></a>Resolving naming conflicts - C name specifications</h3>
769
770    Each Cython module has a single module-level namespace for both Python
771 and  C names. This can be inconvenient if you want to wrap some external
772 C functions  and provide the Python user with Python functions of the same
773 names.   
774 <p>Cython 0.8 provides a couple of different ways of solving this problem. 
775  The best way, especially if you have many C functions to wrap, is probably 
776  to put the extern C function declarations into a different namespace using 
777  the facilities described in the section on <a href="sharing.html">sharing 
778  declarations between Cython modules</a>. </p>
779
780    
781 <p>The other way is to use a <b>c name specification</b> to give different 
782  Cython and C names to the C function. Suppose, for example, that you want 
783 to wrap an external function called <tt>eject_tomato</tt>. If you declare 
784 it as </p>
785
786    
787 <blockquote>        <pre>cdef extern void c_eject_tomato "eject_tomato" (float speed)</pre>
788    </blockquote>
789
790    then its name inside the Cython module will be <tt>c_eject_tomato</tt>, 
791 whereas its name in C will be <tt>eject_tomato</tt>. You can then wrap it 
792 with   
793 <blockquote>        <pre>def eject_tomato(speed):<br>&nbsp; c_eject_tomato(speed)</pre>
794    </blockquote>
795
796    so that users of your module can refer to it as <tt>eject_tomato</tt>. 
797   
798 <p>Another use for this feature is referring to external names that happen 
799  to be Cython keywords. For example, if you want to call an external function 
800  called <tt>print</tt>, you can rename it to something else in your Cython 
801 module.  </p>
802
803    
804 <p>As well as functions, C names can be specified for variables, structs, 
805  unions, enums, struct and union members, and enum values. For example, </p>
806
807    
808 <blockquote>        <pre>cdef extern int one "ein", two "zwei"<br>cdef extern float three "drei"<br><br>cdef struct spam "SPAM":<br>&nbsp; int i "eye"</pre>
809    <tt>cdef enum surprise "inquisition":</tt> <br>
810     <tt>&nbsp; first "alpha"</tt> <br>
811     <tt>&nbsp; second "beta" = 3</tt></blockquote>
812
813      
814 <hr width="100%">  
815 <h3> <a name="PublicDecls"></a>Public Declarations</h3>
816
817    You can make C variables and functions defined in a Cython module accessible 
818  to external C code (or another Cython module) using the <b><tt>public</tt></b> keyword, as follows:   
819 <blockquote><tt>cdef public int spam # public variable declaration</tt>       <p><tt>cdef public void grail(int num_nuns): # public function declaration</tt>   <br>
820     <tt>&nbsp;&nbsp;&nbsp; ...</tt></p>
821   </blockquote>
822
823    If there are any <tt>public</tt> declarations in a Cython module, a <b>.h</b> file is generated containing equivalent C declarations for inclusion in other
824  C code.   
825 <p>Cython also generates a <b>.pxi</b> file containing Cython versions of the
826  declarations for inclusion in another Cython module using the <b><a href="#IncludeStatement">include</a></b> statement. If you use this, you
827  will need to arrange for the module using the declarations to be linked
828 against  the module defining them, and for both modules to be available to
829 the dynamic  linker at run time. I haven't tested this, so I can't say how
830 well it will  work on the various platforms. </p>
831
832    
833 <blockquote>NOTE: If all you want to export is an extension type, there is
834  now a better way -- see <a href="sharing.html">Sharing Declarations Between
835  Cython Modules</a>.</blockquote>
836
837      
838 <h2>   <hr width="100%">Extension Types   
839 <hr width="100%"></h2>
840
841    One of the most powerful features of Cython is the ability to easily create 
842  new built-in Python types, called <b>extension types</b>. This is a major 
843  topic in itself, so there is a&nbsp; <a href="extension_types.html">separate 
844  page</a> devoted to it.   
845 <h2>   <hr width="100%">Sharing Declarations Between Cython Modules   
846 <hr width="100%"></h2>
847
848    Cython 0.8 introduces a substantial new set of facilities allowing a Cython 
849  module to easily import and use C declarations and extension types from another
850 Cython module. You can now create a set of co-operating Cython modules just
851 as easily as you can create a set of co-operating Python modules. There is
852 a <a href="sharing.html">separate page</a> devoted to this topic.   
853 <h2>   <hr width="100%"><a name="Limitations"></a>Limitations   
854 <hr width="100%"></h2>
855
856      
857 <h3> <a name="Unsupported"></a>Unsupported Python features</h3>
858
859    Cython is not quite a full superset of Python. The following restrictions 
860  apply:   
861 <blockquote> <li> Function definitions (whether using <b>def</b> or <b>cdef</b>)
862  cannot be nested within other function definitions.<br>
863    </li>
864   &nbsp; <li> Class definitions can only appear at the top level of a module,
865  not inside a function.<br>
866    </li>
867   &nbsp; <li> The<tt> import *</tt> form of import is not allowed anywhere
868  (other forms of the import statement are fine, though).<br>
869    </li>
870   &nbsp; <li> Generators cannot be defined in Cython.<br>
871      <br>
872    </li>
873     <li> The <tt>globals()</tt> and <tt>locals()</tt> functions cannot be 
874 used.</li>
875    </blockquote>
876
877    The above restrictions will most likely remain, since removing them would 
878  be difficult and they're not really needed for Cython's intended applications. 
879   
880 <p>There are also some temporary limitations, which may eventually be lifted, including: 
881  </p>
882
883    
884 <blockquote> <li> Class and function definitions cannot be placed inside
885 control structures.<br>
886    </li>
887   &nbsp; <li> In-place arithmetic operators (+=, etc) are not yet supported.<br>
888    </li>
889   &nbsp; <li> List comprehensions are not yet supported.<br>
890    </li>
891   &nbsp; <li> There is no support for Unicode.<br>
892    </li>
893   &nbsp; <li> Special methods of extension types cannot have functioning
894 docstrings.<br>
895      <br>
896    </li>
897     <li> The use of string literals as comments is not recommended at present,
898  because Cython doesn't optimize them away, and won't even accept them in
899 places  where executable statements are not allowed.</li>
900    </blockquote>
901    
902 <h3> <a name="SemanticDifferences"></a>Semantic differences between Python
903  and Cython</h3>
904
905      
906 <h4> Behaviour of class scopes</h4>
907
908    In Python, referring to a method of a class inside the class definition, 
909  i.e. while the class is being defined, yields a plain function object, but
910  in Cython it yields an unbound method<sup><font size="-2"><a href="#Footnote2">2</a></font></sup>. A consequence of this is that the
911 usual idiom for using the classmethod and staticmethod functions, e.g.   
912 <blockquote>        <pre>class Spam:</pre>
913            <pre>&nbsp; def method(cls):<br>&nbsp;&nbsp;&nbsp; ...</pre>
914            <pre>&nbsp; method = classmethod(method)</pre>
915    </blockquote>
916
917    will not work in Cython. This can be worked around by defining the function 
918  <i>outside</i> the class, and then assigning the result of classmethod or
919  staticmethod inside the class, i.e.   
920 <blockquote>        <pre>def Spam_method(cls):<br>&nbsp; ...</pre>
921            <pre>class Spam:</pre>
922            <pre>&nbsp; method = classmethod(Spam_method)</pre>
923    </blockquote>
924
925      
926 <h1>   <hr width="100%"><font size="+0">Footnotes</font>  <hr width="100%"></h1>
927
928    <a name="Footnote1"></a>1. A problem with const could arise if you have 
929 something like   
930 <blockquote>        <pre>cdef extern from "grail.h":<br>&nbsp; char *nun</pre>
931    </blockquote>
932
933    where grail.h actually contains   
934 <blockquote>        <pre>extern const char *nun;</pre>
935    </blockquote>
936
937    and you do   
938 <blockquote>        <pre>cdef void languissement(char *s):<br>&nbsp; #something that doesn't change s</pre>
939            <pre>...</pre>
940            <pre>languissement(nun)</pre>
941    </blockquote>
942
943    which will cause the C compiler to complain. You can work around it by 
944 casting  away the constness:   
945 <blockquote>        <pre>languissement(&lt;char *&gt;nun)</pre>
946    </blockquote>
947
948      
949 <hr width="100%"><a name="Footnote2"></a>2. The reason for the different behaviour
950 of class scopes is that Cython-defined Python functions are PyCFunction objects,
951 not PyFunction objects, and are not recognised by the machinery that creates
952 a bound or unbound method when a function is extracted from a class. To get
953 around this, Cython wraps each method in an unbound method object itself before
954 storing it in the class's dictionary. <br>
955
956   &nbsp; <br>
957
958   <br>
959
960  </body></html>