Browse Source

DEB pyrex: Added to repository.

Signed-off-by: Slávek Banko <>
Slávek Banko 2 months ago
Signed by: SlavekB GPG Key ID: 608F5293A04BE668
  1. 8
  2. 1871
  3. 24
  4. 15
  5. 21
  6. 14
  7. 10
  8. 19
  9. 1
  10. 11
  11. 13
  12. 21
  13. 1
  14. 7
  15. 1
  16. 35
  17. 1
  18. 30
  19. 1
  20. 5
  21. 9
  22. 39
  23. 18
  24. 13
  25. 5
  26. 7
  27. 8
  28. 22
  29. 149
  30. 75
  31. 17
  32. 53
  33. 1118
  34. 1079
  35. 294
  36. 342
  37. 78
  38. 1124
  39. 7
  40. 43
  41. 70
  42. 1
  43. 33
  44. 173
  45. 7
  46. 15
  47. 829
  48. 1485
  49. 276
  50. 94
  51. 546
  52. 4
  53. 77
  54. 3954
  55. 9
  56. BIN
  57. 145
  58. 564
  59. 1678
  60. 69
  61. 3249
  62. 5
  63. 2142
  64. 974
  65. 390
  66. 1342
  67. 629
  68. 1
  69. 0
  70. 20
  71. 11
  72. 194
  73. 79
  74. 22
  75. 63
  76. 85
  77. 135
  78. 34
  79. 24
  80. 64
  81. 3345
  82. 0
  83. 135
  84. 12
  85. 109
  86. 156
  87. 52
  88. 192
  89. 326
  90. 557
  91. 377
  92. 22
  93. 154
  94. 253
  95. 40
  96. 24
  97. 74
  98. 0
  99. 55
  100. 0
  101. 37
  102. 164
  103. 1
  104. 1
  105. 69
  106. 8
  107. 8
  108. 8
  109. 15
  110. 7
  111. 7
  112. 49
  113. 333
  114. 1
  115. 35
  116. 44
  117. 24
  118. 1
  119. 15
  120. 23
  121. 1
  122. 43
  123. 10
  124. 5
  125. 7
  126. 93
  127. 1
  128. 3
  129. 2
  130. 10
  131. 6
  132. 48
  133. BIN


@ -0,0 +1,8 @@
588a14055d1691eb3d0a14d69be108c6110fcee7 0.9.8
67efcff42bd53148cfdbb0767c64e1c7a852f82f 0.9.9
f11df44eb1bfa2f7ed609c7affc89461e8aa91f5 0.9.9

File diff suppressed because it is too large
View File


@ -0,0 +1,24 @@
Release Checklist
* Update CHANGES.txt
* Ensure all tests pass
* cd Demos; make test
* make test_setup
* Check version number in Makefile
* Update news in web page
* Commit changes
* Tag release
* cd ..; make tar
* make upload
* make push


@ -0,0 +1,15 @@
python build_ext --inplace
test: all
python 20
cd callback; $(MAKE) test
@echo Cleaning Demos
@rm -f *.c *.o *.so *~ core
@rm -rf build
@cd callback; $(MAKE) clean
@cd embed; $(MAKE) clean


@ -0,0 +1,21 @@
PYHOME = $(HOME)/pkg/python/version
-I$(PYHOME)/include/python2.2 \
%.c: %.pyx
../bin/pyrexc $<
%.o: %.c
gcc -c -fPIC $(PYINCLUDE) $< %.o
gcc -shared $< -lm -o $@
@echo Cleaning Demos
@rm -f *.c *.o *.so *~ core core.*
@cd callback; $(MAKE) clean
@cd embed; $(MAKE) clean


@ -0,0 +1,14 @@
from distutils.core import setup
#from distutils.extension import Extension
from Pyrex.Distutils.extension import Extension
from Pyrex.Distutils import build_ext
name = 'Demos',
Extension("primes", ["primes.pyx"]),
Extension("spam", ["spam.pyx"]),
Extension("numeric_demo", ["numeric_demo.pyx"]),
cmdclass = {'build_ext': build_ext}


@ -0,0 +1,10 @@
python build_ext --inplace
test: all
@echo Cleaning Demos/callback
@rm -f cheese.c *.o *.so *~ core
@rm -rf build


@ -0,0 +1,19 @@
PYHOME = $(HOME)/pkg/python/version
-I$(PYHOME)/include/python2.2 \
%.c: %.pyx
../../bin/pyrexc $<
%.o: %.c
gcc -c -fPIC $(PYINCLUDE) $< %.o
gcc -shared $< -lm -o $@
@echo Cleaning Demos/callback
@rm -f *.c *.o *.so *~ core core.*


@ -0,0 +1 @@
This example demonstrates how you can wrap a C API that has a callback interface, so that you can pass Python functions to it as callbacks. The files cheesefinder.h and cheesefinder.c represent the C library to be wrapped. The file cheese.pyx is the Pyrex module which wraps it. The file demonstrates how to call the wrapper.


@ -0,0 +1,11 @@
from distutils.core import setup
from distutils.extension import Extension
from Pyrex.Distutils import build_ext
name = 'callback',
Extension("cheese", ["cheese.pyx", "cheesefinder.c"]),
cmdclass = {'build_ext': build_ext}


@ -0,0 +1,13 @@
# Pyrex wrapper for the cheesefinder API
cdef extern from "cheesefinder.h":
ctypedef void (*cheesefunc)(char *name, void *user_data)
void find_cheeses(cheesefunc user_func, void *user_data)
def find(f):
find_cheeses(callback, <void*>f)
cdef void callback(char *name, void *f):


@ -0,0 +1,21 @@
* An example of a C API that provides a callback mechanism.
#include "cheesefinder.h"
static char *cheeses[] = {
"that runny one",
void find_cheeses(cheesefunc user_func, void *user_data) {
char **p = cheeses;
while (*p) {
user_func(*p, user_data);


@ -0,0 +1 @@
typedef void (*cheesefunc)(char *name, void *user_data); void find_cheeses(cheesefunc user_func, void *user_data);


@ -0,0 +1,7 @@
import cheese
def report_cheese(name):
print "Found cheese:", name


@ -0,0 +1 @@


@ -0,0 +1,35 @@
# Makefile for Microsoft C Compiler, building a DLL
CFLAGS = $(PYINCLUDE) /Ox /W3 /GX -nologo
.SUFFIXES: .exe .dll .obj .c .cpp .pyx
$(PYHOME)\Python.exe ../../ $<
all: main.exe
del /Q/F *.obj embedded.h embedded.c main.exe embedded.dll embedded.lib embedded.exp
# When linking the DLL we must explicitly list all of the exports
# There doesn't seem to be an easy way to get DL_EXPORT to have the correct definition
# to do the export for us without breaking the importing of symbols from the core
# python library.
embedded.dll: embedded.obj
link /nologo /DLL /INCREMENTAL:NO $(PYLIB) $** /IMPLIB:$*.lib /DEF:<< /OUT:$*.dll
EXPORTS initembedded
main.exe: main.obj embedded.lib
link /nologo $** $(PYLIB) /OUT:main.exe
embedded.h: embedded.c
main.obj: embedded.h
embedded.obj: embedded.c
$(CC) /MD $(CFLAGS) -c $**
embedded.lib: embedded.dll


@ -0,0 +1 @@
# Makefile for Microsoft compiler statically linking PYVERSION = 2.2 PYHOME = \Python$(PYVERSION:.=) PYINCLUDE = -I$(PYHOME)\include PYLIB = /LIBPATH:$(PYHOME)\libs python22.lib CFLAGS = $(PYINCLUDE) /Ox /W3 /GX -nologo .SUFFIXES: .exe .dll .obj .c .cpp .pyx .pyx.c: $(PYHOME)\Python.exe ../../ $< all: main.exe clean: -del /Q/F *.obj embedded.h embedded.c main.exe main.exe: main.obj embedded.obj link /nologo $** $(PYLIB) /OUT:main.exe embedded.h: embedded.c main.obj: embedded.h


@ -0,0 +1,30 @@
PYHOME = $(HOME)/pkg/python/$(PYVERSION)
-I$(PYHOME)/include/python$(PYVERSION) \
PYLIB = -L$(PYARCH)/lib/python$(PYVERSION)/config \
-lpython$(PYVERSION) \
-ldl -lpthread -lutil -lm
%.c: %.pyx
../../bin/pyrexc $<
%.o: %.c
gcc -c -fPIC $(PYINCLUDE) $< %.o
# gcc -shared $< -lm -o $@
all: main
main: main.o embedded.o
gcc main.o embedded.o $(PYLIB) -o main
@echo Cleaning Demos/embed
@rm -f *~ *.o *.so core core.* embedded.h embedded.c main
embedded.h: embedded.c
main.o: embedded.h


@ -0,0 +1 @@
This example demonstrates how Pyrex-generated code can be called directly from a main program written in C. In this example, the module's initialisation function (called "initembedded", since the module is called "embedded") is called explicitly. This is necessary because the module is not being imported using the normal Python import mechanism. The Windows makefiles were contributed by Duncan Booth <>.


@ -0,0 +1,5 @@
cdef public void spam():
def praise():
print "Spam, glorious spam!"


@ -0,0 +1,9 @@
#include "Python.h"
#include "embedded.h"
int main(int argc, char *argv) {


@ -0,0 +1,39 @@
# This example demonstrates how to access the internals
# of a Numeric array object.
cdef extern from "Numeric/arrayobject.h":
struct PyArray_Descr:
int type_num, elsize
char type
ctypedef class Numeric.ArrayType [object PyArrayObject]:
cdef char *data
cdef int nd
cdef int *dimensions, *strides
cdef object base
cdef PyArray_Descr *descr
cdef int flags
def print_2d_array(ArrayType a):
print "Type:", chr(a.descr.type)
if chr(a.descr.type) <> "f":
raise TypeError("Float array required")
if a.nd <> 2:
raise ValueError("2 dimensional array required")
cdef int nrows, ncols
cdef float *elems, x
nrows = a.dimensions[0]
ncols = a.dimensions[1]
elems = <float *>
hyphen = "-"
divider = ("+" + 10 * hyphen) * ncols + "+"
print divider
for row in range(nrows):
for col in range(ncols):
x = elems[row * ncols + col]
print "| %8f" % x,
print "|"
print divider


@ -0,0 +1,18 @@
def primes(int kmax):
cdef int n, k, i
cdef int p[1000]
result = []
if kmax > 1000:
kmax = 1000
k = 0
n = 2
while k < kmax:
i = 0
while i < k and n % p[i] <> 0:
i = i + 1
if i == k:
p[k] = n
k = k + 1
n = n + 1
return result


@ -0,0 +1,13 @@
def primes(kmax):
p = []
k = 0
n = 2
while k < kmax:
i = 0
while i < k and n % p[i] <> 0:
i = i + 1
if i == k:
k = k + 1
n = n + 1
return p


@ -0,0 +1,5 @@
import Numeric
import numeric_demo
a = Numeric.array([[1.0, 3.5, 8.4], [2.3, 6.6, 4.1]], "f")


@ -0,0 +1,7 @@
import sys
from primes import primes
if len(sys.argv) >= 2:
n = int(sys.argv[1])
n = 1000
print primes(n)


@ -0,0 +1,8 @@
from spam import Spam
s = Spam()
print "Created:", s
print "Amount =", s.get_amount()
s = None


@ -0,0 +1,22 @@
# Example of an extension type.
cdef class Spam:
cdef int amount
def __cinit__(self):
self.amount = 0
def __dealloc__(self):
print self.amount, "tons of spam is history."
def get_amount(self):
return self.amount
def set_amount(self, new_amount):
self.amount = new_amount
def describe(self):
print self.amount, "tons of spam!"


@ -0,0 +1,149 @@
<!DOCTYPE html PUBLIC "-//w3c//dtd html 4.0 transitional//en">
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta name="GENERATOR" content="Mozilla/4.51 (Macintosh; I; PPC) [Netscape]">
<title>About Pyrex</title></head>
<hr width="100%">Pyrex</h1></center>
<center><i><font size="+1">A language for writing Python extension modules</font></i>
<hr width="100%"></center>
What is Pyrex all about?</h2>
Pyrex is a language specially designed for writing Python extension modules.
It's designed to bridge the gap between the nice, high-level, easy-to-use
world of Python and the messy, low-level world of C.
<p>You may be wondering why anyone would want a special language for this.
Python is really easy to extend using C or C++, isn't it? Why not just
write your extension modules in one of those languages?
</p><p>Well, if you've ever written an extension module for Python, you'll
know that things are not as easy as all that. First of all, there is a
fair bit of boilerplate code to write before you can even get off the ground.
Then you're faced with the problem of converting between Python and C data
types. For the basic types such as numbers and strings this is not too
bad, but anything more elaborate and you're into picking Python objects
apart using the Python/C API calls, which requires you to be meticulous
about maintaining reference counts, checking for errors at every step and
cleaning up properly if anything goes wrong. Any mistakes and you have
a nasty crash that's very difficult to debug.
</p><p>Various tools have been developed to ease some of the burdens of producing
extension code, of which perhaps <a href="">SWIG</a>
is the best known. SWIG takes a definition file consisting of a mixture
of C code and specialised declarations, and produces an extension module.
It writes all the boilerplate for you, and in many cases you can use it
without knowing about the Python/C API. But you need to use API calls if
any substantial restructuring of the data is required between Python and
</p><p>What's more, SWIG gives you no help at all if you want to create a new
built-in Python <i>type. </i>It will generate pure-Python classes which
wrap (in a slightly unsafe manner) pointers to C data structures, but creation
of true extension types is outside its scope.
</p><p>Another notable attempt at making it easier to extend Python is <a href="">PyInline</a>
, inspired by a similar facility for Perl. PyInline lets you embed pieces
of C code in the midst of a Python file, and automatically extracts them
and compiles them into an extension. But it only converts the basic types
automatically, and as with SWIG,&nbsp; it doesn't address the creation
of new Python types.
</p><p>Pyrex aims to go far beyond what any of these previous tools provides.
Pyrex deals with the basic types just as easily as SWIG, but it also lets
you write code to convert between arbitrary Python data structures and
arbitrary C data structures, in a simple and natural way, without knowing
<i>anything</i> about the Python/C API. That's right -- <i>nothing at all</i>!
Nor do you have to worry about reference counting or error checking --
it's all taken care of automatically, behind the scenes, just as it is
in interpreted Python code. And what's more, Pyrex lets you define new
<i>built-in</i> Python types just as easily as you can define new classes
in Python.
</p><p>Sound too good to be true? Read on and find out how it's done.
The Basics of Pyrex</h2>
The fundamental nature of Pyrex can be summed up as follows: <b>Pyrex is
Python with C data types</b>.
<p><i>Pyrex is Python:</i> Almost any piece of Python code is also valid
Pyrex code. (There are a few limitations, but this approximation will serve
for now.) The Pyrex compiler will convert it into C code which makes equivalent
calls to the Python/C API. In this respect, Pyrex is similar to the former
Python2C project (to which I would supply a reference except that it no
longer seems to exist).
</p><p><i>...with C data types.</i> But Pyrex is much more than that, because
parameters and variables can be declared to have C data types. Code which
manipulates Python values and C values can be freely intermixed, with conversions
occurring automatically wherever possible. Reference count maintenance
and error checking of Python operations is also automatic, and the full
power of Python's exception handling facilities, including the try-except
and try-finally statements, is available to you -- even in the midst of
manipulating C data.
</p><p>Here's a small example showing some of what can be done. It's a routine
for finding prime numbers. You tell it how many primes you want, and it
returns them as a Python list.
</p><blockquote><b><tt><font size="+1">primes.pyx</font></tt></b></blockquote>
<pre>&nbsp;1&nbsp; def primes(int kmax):<br>&nbsp;2&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; cdef int n, k, i<br>&nbsp;3&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; cdef int p[1000]<br>&nbsp;4&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; result = []<br>&nbsp;5&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; if kmax &gt; 1000:<br>&nbsp;6&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; kmax = 1000<br>&nbsp;7&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; k = 0<br>&nbsp;8&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; n = 2<br>&nbsp;9&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; while k &lt; kmax:<br>10&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; i = 0<br>11&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; while i &lt; k and n % p[i] &lt;&gt; 0:<br>12&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; i = i + 1<br>13&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; if i == k:<br>14&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; p[k] = n<br>15&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; k = k + 1<br>16&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; result.append(n)<br>17&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; n = n + 1<br>18&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; return result</pre>
You'll see that it starts out just like a normal Python function definition,
except that the parameter <b>kmax</b> is declared to be of type <b>int</b>
. This means that the object passed will be converted to a C integer (or
a TypeError will be raised if it can't be).
<p>Lines 2 and 3 use the <b>cdef</b> statement to define some local C variables.
Line 4 creates a Python list which will be used to return the result. You'll
notice that this is done exactly the same way it would be in Python. Because
the variable <b>result</b> hasn't been given a type, it is assumed to hold
a Python object.
</p><p>Lines 7-9 set up for a loop which will test candidate numbers for primeness
until the required number of primes has been found. Lines 11-12, which
try dividing a candidate by all the primes found so far, are of particular
interest. Because no Python objects are referred to, the loop is translated
entirely into C code, and thus runs very fast.
</p><p>When a prime is found, lines 14-15 add it to the p array for fast access
by the testing loop, and line 16 adds it to the result list. Again, you'll
notice that line 16 looks very much like a Python statement, and in fact
it is, with the twist that the C parameter <b>n</b> is automatically converted
to a Python object before being passed to the <b>append</b> method. Finally,
at line 18, a normal Python <b>return</b> statement returns the result
</p><p>Compiling primes.pyx with the Pyrex compiler produces an extension module
which we can try out in the interactive interpreter as follows:
<pre>&gt;&gt;&gt; import primes<br>&gt;&gt;&gt; primes.primes(10)<br>[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]<br>&gt;&gt;&gt;</pre>
See, it works! And if you're curious about how much work Pyrex has saved
you, take a look at the <a href="primes.c">C code generated for this module</a>
Language Details</h2>
For more about the Pyrex language, see the <a href="LanguageOverview.html">Language
Overview</a> .
Future Plans</h2>
Pyrex is not finished. Substantial tasks remaining include:
Support for certain Python language features which are planned but not
yet implemented. See the <a href="Manual/Limitations.html">Limitations</a>
section of the <a href="LanguageOverview.html">Language Overview</a> for a current
C++ support. This could be a very big can of worms - careful thought required
before going there.</li>
Reading C/C++ header files directly would be very nice, but there are some
severe problems that I will have to find solutions for first, such as what
to do about preprocessor macros. My current thinking is to use a separate
tool to convert .h files into Pyrex declarations, possibly with some manual


@ -0,0 +1,75 @@
<!DOCTYPE doctype PUBLIC "-//w3c//dtd html 4.0 transitional//en">
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta name="GENERATOR" content="Mozilla/4.51 (Macintosh; I; PPC) [Netscape]"><title>FAQ.html</title></head>
<center> <h1> <hr width="100%">Pyrex FAQ
<hr width="100%"></h1>
<h2> Contents</h2>
<li> <b><a href="#CallCAPI">How do I call Python/C API routines?</a></b></li>
<li> <b><a href="#NullBytes">How do I convert a C string containing null
bytes to a Python string?</a></b></li>
<li> <b><a href="#NumericAccess">How do I access the data inside a Numeric
array object?</a></b></li>
<li><b><a href="#Rhubarb">Pyrex says my extension type object has no attribute
'rhubarb', but I know it does. What gives?</a></b></li><li><a style="font-weight: bold;" href="#Quack">Python says my extension type has no method called 'quack', but I know it does. What gives?</a><br>
<hr width="100%"> <h2> <a name="CallCAPI"></a>How do I call Python/C API routines?</h2>
Declare them as C functions inside a <tt>cdef extern from</tt> block.
Use the type name <tt>object</tt> for any parameters and return types which
are Python object references. Don't use the word <tt>const</tt> anywhere.
Here is an example which defines and uses the <tt>PyString_FromStringAndSize</tt> routine:
<blockquote><tt>cdef extern from "Python.h":</tt> <br>
<tt>&nbsp;&nbsp;&nbsp; object PyString_FromStringAndSize(char *, int)</tt> <p><tt>cdef char buf[42]</tt> <br>
<tt>my_string = PyString_FromStringAndSize(buf, 42)</tt></p>
<h2> <a name="NullBytes"></a>How do I convert a C string containing null
bytes to a Python string?</h2>
Put in a declaration for the <tt>PyString_FromStringAndSize</tt> API routine
and use that<tt>.</tt> See <a href="#CallCAPI">How do I call Python/C API
routines?</a> <h2> <a name="NumericAccess"></a>How do I access the data inside a Numeric
array object?</h2>
Use a <tt>cdef extern from</tt> block to include the Numeric header file
and declare the array object as an external extension type. The following
code illustrates how to do this:
<blockquote><tt>cdef extern from "Numeric/arrayobject.h":</tt> <p><tt>&nbsp;&nbsp;&nbsp; struct PyArray_Descr:</tt> <br>
<tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; int type_num, elsize</tt> <br>
<tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; char type</tt> </p>
<p><tt>&nbsp;&nbsp;&nbsp; ctypedef class Numeric.ArrayType [object PyArrayObject]</tt><tt>:</tt> <br>
<tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; cdef char *data</tt> <br>
<tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; cdef int nd</tt> <br>
<tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; cdef int *dimensions,
*strides</tt> <br>
<tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; cdef object base</tt>
<tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; cdef PyArray_Descr *descr</tt> <br>
<tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; cdef int flags<br>
<p>For more information about external extension types, see the <a href="extension_types.html#ExternalExtTypes">"External Extension Types"</a>
section of the <a href="extension_types.html">"Extension Types"</a> documentation
<tt> </tt> </p>
<h2><a name="Rhubarb"></a>Pyrex says my extension type object has no attribute
'rhubarb', but I know it does. What gives?</h2>
You're probably trying to access it through a reference which Pyrex thinks
is a generic Python object. You need to tell Pyrex that it's a reference
to your extension type by means of a declaration. For example,<br>
<blockquote><tt>cdef class Vegetables:</tt><br>
<tt>&nbsp; &nbsp; cdef int rhubarb</tt><br>
<tt>cdef Vegetables veg</tt><br>
<tt>veg.rhubarb = 42</tt><br>
Also see the <a href="Manual/extension_types.html#ExtTypeAttrs">"Attributes"</a>
section of the <a href="Manual/extension_types.html">"Extension
Types"</a> documentation page.<br>
<h2><a name="Quack"></a>Python says my extension type has no method called 'quack', but I know it does. What gives?</h2>
You may have declared the method using <span style="font-family: monospace;">cdef</span> instead of <span style="font-family: monospace;">def</span>. Only functions and methods declared with <span style="font-family: monospace;">def</span> are callable from Python code.<br><br>


@ -0,0 +1,17 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "">
<html><head><meta content="text/html; charset=ISO-8859-1" http-equiv="content-type"><title>Pyrex Language Overview</title></head>
<hr width="100%">Overview of the Pyrex Language&nbsp;
<hr width="100%"></h1>
This is a combined tutorial and reference manual that describes the extensions to the Python language
made by Pyrex.<h2> Contents</h2>
<ul><li><a href="Manual/source_files.html">Source Files and Compilation</a> <span style="color: rgb(0, 153, 0);">(Section added in 0.9.5)</span><br>
</li><li><a href="Manual/basics.html">Language Basics</a></li><li> <a href="Manual/external.html">Interfacing with External C Code</a></li><li> <a href="Manual/extension_types.html">Extension Types</a></li><li><a href="Manual/special_methods.html">Special Methods of Extension Types</a></li><li> <a href="Manual/sharing.html">Sharing Declarations Between Pyrex Modules</a></li><li><a href="Manual/using_with_c++.html">Using Pyrex with C++</a></li><li> <a href="Manual/Limitations.html">Limitations</a></li></ul>---</body></html>


@ -0,0 +1,53 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "">
<html><head><meta content="text/html; charset=ISO-8859-1" http-equiv="content-type"><title>Limitations</title></head>
<body><h1><hr width="100%">
<a name="Limitations"></a>Limitations <hr width="100%"></h1><h2> <a name="Unsupported"></a>Unsupported
Python features</h2>
Pyrex is not quite a full superset of Python. The following
restrictions apply: <blockquote> <li> Function
definitions (whether using <b>def</b> or <b>cdef</b>)
cannot be nested within other function definitions.<br> </li>
&nbsp; <li> Class definitions can only appear at the top
level of a module, not inside a function.<br> </li>
&nbsp; <li> The<tt> import *</tt> form of import
is not allowed anywhere (other forms of the import statement are fine,
though).<br> </li> &nbsp; <li> Generators
cannot be defined in Pyrex.<br> <br> </li> <li>
The <tt>globals()</tt> and <tt>locals()</tt>
functions cannot be used.</li> </blockquote> The above
restrictions will most likely remain, since removing them would be
difficult and they're not really needed for Pyrex's intended
applications. <p>There are also some temporary limitations,
which may eventually be lifted, including: </p> <blockquote>
<li> Class and function definitions cannot be placed inside
control structures.<br> </li> &nbsp; <li> List comprehensions are not yet
supported.<br> </li> &nbsp; <li> There is no
support for Unicode.<br> </li> &nbsp; <li>
Special methods of extension types cannot have functioning
docstrings.<br> <br> </li> <li> The use of
string literals as comments is not recommended at present, because they are not accepted in
places where executable statements are not allowed.</li></blockquote><hr style="width: 100%; height: 2px;"><h2><a name="SemanticDifferences"></a>Semantic
differences between Python and Pyrex</h2> <h3> Behaviour
of class scopes</h3> In Python, referring to a method of a class
inside the class definition, i.e. while the class is being defined,
yields a plain function object, but in Pyrex it yields an unbound method<sup><font size="-2"><a href="#Footnote1">1</a></font></sup>.
A consequence of this is that the
usual idiom for using the classmethod and staticmethod functions, e.g. <blockquote>
<pre>class Spam:</pre> <pre>&nbsp; def method(cls):<br>&nbsp;&nbsp;&nbsp; ...</pre><pre>&nbsp; method = classmethod(method)</pre>
will not work in Pyrex. This can be worked around by defining the
function <i>outside</i> the class, and then assigning the
result of classmethod or staticmethod inside the class, i.e. <blockquote>
<pre>def Spam_method(cls):<br>&nbsp; ...</pre> <pre>class Spam:</pre><pre>&nbsp; method = classmethod(Spam_method)</pre>
</blockquote> <hr width="100%"><span style="font-weight: bold;">Footnotes</span><br><hr style="width: 100%; height: 2px;"><a name="Footnote1"></a>1.
The reason for the different
of class scopes is that Pyrex-defined Python functions are PyCFunction
not PyFunction objects, and are not recognised by the machinery that
a bound or unbound method when a function is extracted from a class. To
around this, Pyrex wraps each method in an unbound method object itself
storing it in the class's dictionary.<br><br>--- </body></html>

File diff suppressed because it is too large
View File

File diff suppressed because it is too large
View File


@ -0,0 +1,294 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "">
<html><head><meta content="text/html; charset=ISO-8859-1" http-equiv="content-type"><title>Interfacing with External C Code</title></head>
<body><h1><hr style="width: 100%; height: 2px;"><a name="InterfacingWithExternal"></a>Interfacing with
External C Code <hr width="100%"></h1><ul><li>
<a href="#ExternDecls">External declarations</a></li><ul><li>
<a href="#ReferencingHeaders">Referencing C header files</a></li><li>
<a href="#StructDeclStyles">Styles of struct/union/enum
declaration</a></li><li> <a href="#AccessingAPI">Accessing
Python/C API routines</a></li><li><a href="#SpecialTypes">Special Types</a><span style="color: rgb(255, 0, 0);"> <span style="color: rgb(255, 102, 0);">(New in 0.9.6)</span></span></li><li><a href="#CallingConventions">Windows Calling Conventions</a><span style="color: rgb(255, 0, 0);"> <span style="color: rgb(255, 102, 0);">(New in 0.9.6)</span></span></li><li>
<a href="#CNameSpecs">Resolving naming conflicts - C name
specifications</a></li></ul><li><a href="#Using_Pyrex_Declarations_from_C">Using Pyrex
declarations from C</a></li><ul><li> <a href="#PublicDecls">Public declarations</a></li></ul><ul><li><a href="#C_API_Declarations">C API declarations</a><span style="color: rgb(255, 0, 0);"> <span style="color: rgb(255, 102, 0);">(New in 0.9.6)</span></span></li><li><a href="#Multiple_public_and_api_declarations">Multiple public and API declarations</a><span style="color: rgb(255, 0, 0);"> (New in</span></li><li><a href="#Acquiring_and_Releasing_the_GIL">Acquiring and Releasing the GIL</a><span style="color: rgb(255, 0, 0);"> <span style="color: rgb(255, 102, 0);">(New in 0.9.6)</span></span></li></ul></ul>
One of the main uses of Pyrex is wrapping existing libraries of C code.
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 use. <p>You can also use <a href="#PublicDecls">public declarations</a> to make C
functions and variables defined in a Pyrex module available to external
C code. The need for this is expected to be less frequent, but you
might want to do it, for example, if you are embedding Python in
another application as a scripting language. Just as a Pyrex module can
be used as a bridge to
allow Python code to call C code, it can also be used to allow C code
call Python code.</p><hr style="width: 100%; height: 2px;"> <h2> <a name="ExternDecls"></a>External
declarations</h2> By default, C functions and variables declared
at the module level are local to the module (i.e. they have the C <b>static</b>
storage class). They can also be declared <b>extern</b> to
specify that they are defined elsewhere, for example: <blockquote>
<pre>cdef extern int spam_counter</pre> <pre>cdef extern void order_spam(int tons)</pre></blockquote>
<a name="ReferencingHeaders"></a>Referencing C
header files</h3> When you use an extern definition on its own as
in the examples above, Pyrex includes a declaration for it in the
generated C file. This can cause problems if the declaration doesn't
exactly match the declaration that will be seen by other C code. If
you're wrapping an existing C library, for example, it's important that
the generated C code is compiled with exactly the same declarations as
the rest of the library. <p>To achieve this, you can tell Pyrex
that the declarations are to be found in a C header file, like this: </p>
<blockquote> <pre>cdef extern from "spam.h":</pre> <pre>&nbsp;&nbsp;&nbsp; int spam_counter</pre><pre>&nbsp;&nbsp;&nbsp; void order_spam(int tons)</pre>
</blockquote> The <b>cdef extern from</b> clause
does three things: <ol><li> It directs Pyrex to place a <b>#include</b>
statement for the named header file in the generated C code.<br> </li>
&nbsp; <li> It prevents Pyrex from generating any C code for
the declarations found in the associated block.<br> </li>
&nbsp; <li> It treats all declarations within the block as
though they
started with <b>cdef extern</b>.</li></ol>
It's important to understand that Pyrex does <i>not</i>
itself read the C header file, so you still need to provide Pyrex
versions of any declarations from it that you use. However, the Pyrex
declarations don't always have to
exactly match the C ones, and in some cases they shouldn't or can't. In
particular: <ol><li> Don't use <b>const</b>.
Pyrex doesn't know anything about const,
so just leave it out. Most of the time this shouldn't cause any
although on rare occasions you might have to use a cast.<sup><a href="#Footnote1"> 1</a></sup><br> </li>
&nbsp; <li> Leave out any platform-specific extensions to C
declarations such as <b>__declspec()</b>.<br> </li>
&nbsp; <li> If the header file declares a big struct and you
only want
to use a few members, you only need to declare the members you're
interested in. Leaving the rest out doesn't do any harm, because the C
compiler will use the full definition from the header file.<br> <br>
In some cases, you might not need <i>any</i> of the
struct's members, in
which case you can just put <tt>pass</tt> in the body of
the struct declaration,
e.g.<br> <br> <tt>&nbsp; &nbsp; cdef extern
from "foo.h":<br> &nbsp; &nbsp; &nbsp; &nbsp;
struct spam:<br> &nbsp; &nbsp; &nbsp; &nbsp;
&nbsp; &nbsp; pass</tt><br> <br>
Note that you can only do this inside a <b>cdef extern from</b>
block; struct
declarations anywhere else must be non-empty.<br> <br> </li><li>
If the header file uses typedef names such as <b>size_t </b>to
refer to platform-dependent flavours of numeric types, you will need a
corresponding <b>ctypedef</b> statement, but you don't
need to match the type exactly, just use something of the right general
kind (int, float, etc). For example,</li><ol><pre>ctypedef int size_t</pre></ol>
will work okay whatever the actual size of a size_t is (provided the
header file defines it correctly). <br> &nbsp; <li>
If the header file uses macros to define constants, translate them into
a dummy <b>enum</b> declaration.<br> </li>
&nbsp; <li> If the header file defines a function using a
macro, declare it as though it were an ordinary function, with
appropriate argument and
result types.</li></ol> A few more tricks and tips: <ul><li>
If you want to include a C header because it's needed by another
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></ul> <ul><ul><tt>cdef extern
from "spam.h":</tt><br><tt>&nbsp;&nbsp;&nbsp;
pass</tt></ul></ul> <ul><li> If you want
to include some external declarations, but don't want to specify a
header file (because it's included by some other header that you've
already included) you can put <tt>*</tt> in place of the
header file name:</li></ul> <blockquote> <blockquote><tt>cdef
extern from *:</tt> <br> <tt>&nbsp;&nbsp;&nbsp;
...</tt></blockquote> </blockquote> <h3> <a name="StructDeclStyles"></a>Styles of struct, union
and enum declaration</h3> There are two main ways that structs,
unions and enums can be declared in C header files: using a tag name,
or using a typedef. There are also some variations based on various
combinations of these. <p>It's important to make the Pyrex
declarations match the style used in the
header file, so that Pyrex can emit the right sort of references to the
in the code it generates. To make this possible, Pyrex provides two
syntaxes for declaring a struct, union or enum type. The style
above corresponds to the use of a tag name. To get the other style, you
the declaration with <b>ctypedef</b>, as illustrated
below. </p> <p>The following table shows the various
possible styles that can be found in a header file, and the
corresponding Pyrex declaration that you should put in the <b>cdef
exern from </b>block. Struct declarations are used as an
example; the same applies equally to union and enum declarations. </p>
<p>Note that in all the cases below, you refer to the type in
Pyrex code simply
as <tt><font size="+1">Foo</font></tt>,
not <tt><font size="+1">struct Foo</font></tt>.
</p><table cellpadding="5"> <tbody>
<tr bgcolor="#8cbc1c" valign="top"> <td bgcolor="#8cbc1c">&nbsp;</td> <td bgcolor="#ff9933" nowrap="nowrap"><b>C code</b></td>
<td bgcolor="#66cccc" valign="top"><b>Possibilities
for corresponding Pyrex code</b></td> <td bgcolor="#99cc33" valign="top"><b>Comments</b></td>
</tr> <tr bgcolor="#8cbc1c" valign="top"> <td>1</td>
<td bgcolor="#ff9900"><tt>struct Foo {</tt> <br>
<tt>&nbsp; ...</tt> <br> <tt>};</tt></td>
<td bgcolor="#66cccc"><tt>cdef struct Foo:</tt>
<br> <tt>&nbsp; ...</tt></td> <td>Pyrex
will refer to the type as <tt>struct Foo </tt>in the
generated C code<tt>.</tt></td> </tr> <tr bgcolor="#8cbc1c" valign="top"> <td valign="top">2</td>
<td bgcolor="#ff9900" nowrap="nowrap"><tt>typedef
struct {</tt> <br> <tt>&nbsp; ...</tt> <br>
<tt>} Foo;</tt></td> <td bgcolor="#66cccc" valign="top"><tt>ctypedef struct Foo:</tt> <br>
<tt>&nbsp; ...</tt></td> <td valign="top">Pyrex
will refer to the type simply as <tt>Foo</tt>
in the generated C code.</td> </tr> <tr bgcolor="#8cbc1c" valign="top"> <td rowspan="2">3</td>
<td rowspan="2" bgcolor="#ff9900" nowrap="nowrap"><tt>typedef
foo {</tt> <br> <tt>&nbsp; ...</tt> <br>
<tt>} Foo;</tt></td> <td bgcolor="#66cccc" nowrap="nowrap" valign="top"><tt>cdef struct
foo:</tt> <br> <tt>&nbsp; ...</tt> <br>
<tt>ctypedef foo Foo #optional</tt></td> <td rowspan="2" valign="top">If the C header uses both a
tag and a typedef with <i>different</i> names, you can use
either form of declaration in Pyrex (although if you need to forward
reference the type, you'll have to use
the first form).</td> </tr> <tr> <td bgcolor="#66cccc"><tt>ctypedef struct Foo:</tt> <br>
<tt>&nbsp; ...</tt></td> </tr> <tr bgcolor="#8cbc1c" valign="top"> <td>4</td>
<td bgcolor="#ff9900" nowrap="nowrap"><tt>typedef
struct Foo {</tt> <br> <tt>&nbsp; ...</tt>
<br> <tt>} Foo;</tt></td> <td bgcolor="#66cccc" valign="top"><tt>cdef struct
Foo:</tt> <br> <tt>&nbsp; ...</tt></td>
<td>If the header uses the <i>same</i> name for the
tag and the typedef, you won't be able to include a <b>ctypedef</b>
for it -- but then, it's not
necessary.</td> </tr> </tbody> </table> <h3>
<a name="AccessingAPI"></a>Accessing
Python/C API routines</h3> One particular use of the <b>cdef
extern from</b> statement is for gaining access to routines in
the Python/C API. For example, <blockquote> <pre>cdef extern from "Python.h":</pre>
<pre>&nbsp;&nbsp;&nbsp; object PyString_FromStringAndSize(char *s, Py_ssize_t len)</pre></blockquote>
will allow you to create Python strings containing
null bytes. <h3> <a name="SpecialTypes"></a>Special
Types</h3><p>Pyrex predefines the name <span style="font-family: monospace;">Py_ssize_t</span>
for use with Python/C API routines. To make your extensions compatible
with 64-bit systems, you should always use this type where it is
specified in the documentation of Python/C API routines.</p><h3><a name="CallingConventions"></a>Windows Calling
Conventions</h3><p>The <span style="font-family: monospace;">__stdcall</span>, <span style="font-family: monospace;">__fastcall</span> and <span style="font-family: monospace;">__cdecl</span> calling
convention specifiers can be used in Pyrex, with the same syntax as
used by C compilers on Windows, for example,</p><pre style="margin-left: 40px;">cdef extern int __stdcall FrobnicateWindow(long handle)<br><br>cdef void (__stdcall *callback)(void *)<br></pre>If
__stdcall is used, the function is only considered compatible with
other __stdcall functions of the same signature.<br><br> <hr width="100%"> <h2> <a name="CNameSpecs"></a>Resolving
naming conflicts - C name specifications</h2> Each Pyrex module
has a single module-level namespace for both Python
and C names. This can be inconvenient if you want to wrap some external
C functions and provide the Python user with Python functions of the
names. <p>Pyrex 0.8 provides a couple of different ways of
solving this problem. The best way, especially if you have many C
functions to wrap, is probably to put the extern C function
declarations into a different namespace using the facilities described
in the section on <a href="sharing.html">sharing
declarations between Pyrex modules</a>. </p> <p>The
other way is to use a <b>c name specification</b> to give
different Pyrex and C names to the C function. Suppose, for example,
that you want to wrap an external function called <tt>eject_tomato</tt>.
If you declare it as </p> <blockquote> <pre>cdef extern void c_eject_tomato "eject_tomato" (float speed)</pre>
</blockquote> then its name inside the Pyrex module will be <tt>c_eject_tomato</tt>,
whereas its name in C will be <tt>eject_tomato</tt>. You
can then wrap it with <blockquote> <pre>def eject_tomato(speed):<br>&nbsp; c_eject_tomato(speed)</pre>
</blockquote> so that users of your module can refer to it as <tt>eject_tomato</tt>.
<p>Another use for this feature is referring to external names
that happen to be Pyrex keywords. For example, if you want to call an
external function called <tt>print</tt>, you can rename it
to something else in your Pyrex module. </p> <p>As well
as functions, C names can be specified for variables, structs, unions,
enums, struct and union members, and enum values. For example, </p>
<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><tt>cdef
enum surprise "inquisition":</tt> <br> <tt>&nbsp;
first "alpha"</tt> <br> <tt>&nbsp; second
"beta" = 3</tt></blockquote> <hr width="100%">
<h2><a name="Using_Pyrex_Declarations_from_C"></a>Using
Pyrex Declarations from C</h2>Pyrex
provides two methods for making C declarations from a Pyrex module
available for use by external C code &#8211; public declarations and C API
declarations.<br><br><div style="margin-left: 40px;"><span style="font-weight: bold;">NOTE:</span> You do <span style="font-style: italic;">not</span> need to use
either of these to make declarations from one Pyrex module available to
another Pyrex module &#8211; you should use the <span style="font-weight: bold;">cimport</span> statement
for that. <a href="sharing.html">Sharing Declarations
Between Pyrex Modules</a>.</div><h3><a name="PublicDecls"></a>Public Declarations</h3>
You can make C types, variables and functions defined in a Pyrex module
accessible to C code that is linked with the module, by declaring them
with the <b><tt>public</tt></b> keyword: <blockquote><tt>cdef
public struct Bunny: # public type declaration<br>&nbsp;
&nbsp; int vorpalness<br><br>cdef public int spam #
public variable declaration</tt> <p><tt>cdef public
void grail(Bunny *): # public function declaration</tt> <br>
<tt>&nbsp;&nbsp;&nbsp; ...</tt></p> </blockquote>
If there are any <tt>public</tt> declarations in a Pyrex
module, a header file called <b><span style="font-style: italic;">modulename</span>.h</b>
file is generated containing equivalent C declarations for inclusion in
other C code.<br><br>Any
C code wanting to make use of these declarations will need to be
linked, either statically or dynamically, with the extension module.<br><br>If
the Pyrex module resides within a package, then the name of the .h file
consists of the full dotted name of the module, e.g. a module called <span style="font-weight: bold;">foo.spam</span> would have
a header file called <span style="font-weight: bold;">foo.spam.h</span>.
<h3><a name="C_API_Declarations"></a>C API
Declarations</h3><p>The other way of making declarations available to C code is to declare them with the <span style="font-family: monospace; font-weight: bold;">api</span>
keyword. You can use this keyword with C functions and extension types. A header file called "<span style="font-weight: bold;"><span style="font-style: italic;">modulename</span>_api.h</span>"
is produced containing declarations of the functions and extension types, and a function
called <span style="font-weight: bold;">import_<span style="font-style: italic;">modulename</span>()</span>.</p><p>C
code wanting to use these functions or extension types needs to include the header and call
the import_<span style="font-style: italic;">modulename</span>()
function. The other functions can then be called and the extension types used as usual.</p><p>Any
<span style="font-family: monospace;">public</span>
C type or extension type declarations in the Pyrex module are also made available when you
include <span style="font-style: italic;">modulename</span>_api.h.</p><table style="text-align: left; width: 100%;" border="0" cellpadding="5" cellspacing="2"><tbody><tr><td style="background-color: rgb(102, 204, 204);"><pre>delorean.pyx</pre></td><td style="background-color: rgb(255, 153, 0);"><pre>marty.c</pre></td></tr><tr><td style="vertical-align: top; background-color: rgb(102, 204, 204);"><pre>cdef public struct Vehicle:<br> int speed<br> float power<br><br>cdef api void activate(Vehicle *v):<br> if v.speed &gt;= 88 \<br> and v.power &gt;= 1.21:<br> print "Time travel achieved"</pre></td><td style="background-color: rgb(255, 153, 0);"><pre>#include "delorean_api.h"<br><br>Vehicle car;<br><br>int main(int argc, char *argv[]) {<br> import_delorean();<br> car.speed = atoi(argv[1]);<br> car.power = atof(argv[2]);&nbsp;<br> activate(&amp;car);<br>}</pre></td></tr></tbody></table><br>Note
that any types defined in the Pyrex module that are used as argument or
return types of the exported functions will need to be declared <span style="font-family: monospace;">public</span>,
otherwise they won't be included in the generated header file, and you
will get errors when you try to compile a C file that uses the header.<br><br>Using the <span style="font-family: monospace;">api</span> method does not require the C code using the declarations to be linked
with the extension module in any way, as the Python import machinery is
used to make the connection dynamically. However, only functions can be
accessed this way, not variables.<br><br>You can use both <span style="font-family: monospace;">public</span> and <span style="font-family: monospace;">api</span> on the same
function to make it available by both methods, e.g.<br><pre style="margin-left: 40px;">cdef public api void belt_and_braces():<br> ...<br></pre>However,
note that you should include <span style="font-weight: bold;">either</span>
<span style="font-style: italic;">modulename</span>.h
<span style="font-weight: bold;">or</span> <span style="font-style: italic;">modulename</span>_api.h in
a given C file, <span style="font-style: italic;">not</span>
both, otherwise you may get conflicting dual definitions.<br><br>If
the Pyrex module resides within a package, then:<br><ul><li>The
name of the header file contains of the full dotted name of the module.</li><li>The
name of the importing function contains the full name with dots
replaced by double underscores.</li></ul>E.g. a module
called <span style="font-weight: bold;">foo.spam</span>
would have an API header file called <span style="font-weight: bold;">foo.spam_api.h</span> and
an importing function called <span style="font-weight: bold;">import_foo__spam()</span>.<br><h3><a name="Multiple_public_and_api_declarations"></a>Multiple public and api declarations</h3>You can declare a whole group of items as <span style="font-style: italic;">public</span> and/or <span style="font-style: italic;">api</span> all at once by enclosing them in a cdef block, for example,<br><pre style="margin-left: 40px;">cdef public api:<br> void order_spam(int tons)<br> char *get_lunch(float tomato_size)<br></pre>This can be a useful thing to do in a <span style="font-family: monospace;">.pxd</span> file (see <a href="sharing.html">Sharing Declarations
Between Pyrex Modules</a>) to make the module's public interface available by all three methods.<br><br><hr style="width: 100%; height: 2px;"><h2><a name="Acquiring_and_Releasing_the_GIL"></a>Acquiring and Releasing the GIL</h2>Pyrex
provides facilities for releasing the Global Interpreter Lock (GIL)
before calling C code, and for acquiring the GIL in functions that are
to be called back from C code that is executed without the GIL.<br><h3>Releasing the GIL</h3>You can release the GIL around a section of code using the<span style="font-family: monospace; font-weight: bold;"> with nogil </span>statement:<br><pre style="margin-left: 40px;">with nogil:<br> &lt;code to be executed with the GIL released&gt;<br></pre>Code in the body of the statement <span style="font-style: italic;">must not manipulate Python objects</span>,
and must
not call anything that manipulates Python objects without first
re-acquiring the GIL. Pyrex attempts to check that these restrictions
are being followed as far as it can, but it may not catch all possible
forms of violation<span style="font-weight: bold;"></span>.<br><br>Any external C functions called inside the block must be declared as <span style="font-family: monospace;">nogil</span> (<a href="#nogil">see below</a>).<br><br><span style="font-weight: bold;">Note</span>:
It may be safe to do some things with Python objects under some
circumstances. Provided steps are taken (such as adequate locking) to
ensure that the objects involved cannot be deallocated by Python code
running in another thread, it is probably safe to access non-Python C
attributes of an extension type, and to pass references to Python
objects to another function that is safe to call with the GIL released.<br><br>However, in the absence of such locking, it is not safe to do <span style="font-style: italic;">anything</span> with Python objects with the GIL released -- not even look at them.<br><h3>Acquiring the GIL</h3>A
C function that is to be used as a callback from C code that is executed
without the GIL needs to acquire the GIL before it can manipulate
Python objects. This can be done by specifying<span style="font-family: monospace; font-weight: bold;"> with gil </span>in the function header:<br><pre style="margin-left: 40px;">cdef void my_callback(void *data) with gil:<br> ...<br></pre><h3><a name="nogil"></a>Declaring a function as callable without the GIL</h3>You can specify <span style="font-family: monospace; font-weight: bold;">nogil</span> in a C function header or function type to declare that it is safe to call without the GIL.<br><br><div style="margin-left: 40px;"><span style="font-family: monospace;">cdef extern int swizzle_the_knob() nogil</span><br></div><br>A block of external functions can be declared <span style="font-family: monospace;">nogil</span> at once.<br><br><div style="margin-left: 40px;"><span style="font-family: monospace;">cdef extern from "somewhere.h" nogil:</span><br style="font-family: monospace;"><div style="margin-left: 40px;"><span style="font-family: monospace;">...</span><br></div></div><br>Note that declaring a function <span style="font-family: monospace;">nogil</span> does <span style="font-style: italic;">not</span>
cause the GIL to be released before calling the function. It simply
allows the function to be called in situations where the GIL is not
held.<br><br>You can also declare a function implemented in Pyrex as <span style="font-family: monospace;">nogil</span>.<br><pre style="margin-left: 40px;">cdef void my_gil_free_func(int spam) nogil:<br> ...</pre>Such a function cannot have any Python local variables, it cannot return a
Python type, and the same restrictions apply to the body of the function as for a<span style="font-family: monospace;"> with nogil </span>block.<br><br>Declaring a function<span style="font-family: monospace;"> with gil </span>also implicitly makes its signature<span style="font-family: monospace;"> nogil</span>.<br><br>
<hr style="width: 100%; height: 2px;"><span style="font-weight: bold;">Footnotes</span>
<hr width="100%"><a name="Footnote1"></a>1.
A problem with const
could arise if you have something like <blockquote> <pre>cdef extern from "grail.h":<br>&nbsp; char *nun</pre>
</blockquote> where grail.h actually contains <blockquote>
<pre>extern const char *nun;</pre> </blockquote> and
you do <blockquote> <pre>cdef void languissement(char *s):<br>&nbsp; #something that doesn't change s</pre>
<pre>...</pre> <pre>languissement(nun)</pre> </blockquote>which
will cause the C compiler to complain. You can work around it by
casting away the constness: <blockquote> <pre>languissement(&lt;char *&gt;nun)&nbsp; <br></pre>


@ -0,0 +1,342 @@
<!DOCTYPE doctype PUBLIC "-//w3c//dtd html 4.0 transitional//en">
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta name="GENERATOR" content="Mozilla/4.61 (Macintosh; I; PPC) [Netscape]">
<title>Sharing Declarations Between Pyrex Modules</title></head>
<hr width="100%">Sharing Declarations Between Pyrex Modules
<hr width="100%"></h1>
This section describes a new set of facilities introduced in Pyrex 0.8
for making C declarations, functions and extension types in one Pyrex module available
for use in another Pyrex module. These facilities are closely modelled on
the Python import mechanism, and can be thought of as a compile-time version
of it.
<h2><a class="mozTocH2" name="mozTocId699652"></a> Contents</h2><ul id="mozToc"><!--mozToc h2 1 h3 2--><li><a href="#mozTocId989010"> Definition and Implementation files</a><ul><li><a href="#mozTocId411233"> What a Definition File contains</a></li><li><a href="#mozTocId20347"> What an Implementation File contains</a></li></ul></li><li><a href="#mozTocId950993"> The <span style="font-family: monospace;">cimport</span> statement</a><ul><li><a href="#mozTocId559554"> Search paths for definition files</a></li><li><a href="#mozTocId478514"> Using <span style="font-family: monospace;">cimport</span> to resolve naming
conflicts</a></li></ul></li><li><a href="#mozTocId937218">Sharing C Functions</a></li><li><a href="#mozTocId825278">Sharing Extension Types</a></li><li><a href="#mozTocId144977">Circular cimports</a></li></ul>
<h2><a class="mozTocH2" name="mozTocId989010"></a> <a name="DefAndImpFiles"></a>Definition and Implementation files</h2>
A Pyrex module can be split into two parts: a <i>definition file</i> with
a <tt>.pxd</tt> suffix, containing C declarations that are to be available
to other Pyrex modules, and an <i>implementation file</i> with a <tt>.pyx</tt>
suffix, containing everything else. When a module wants to use something
declared in another module's definition file, it imports it using the <a href="#CImportStatement"><b>cimport</b> statement</a>.
<h3><a class="mozTocH3" name="mozTocId411233"></a> <a name="WhatDefFileContains"></a>What a Definition File contains</h3>
A definition file can contain:
<li> Any kind of C type declaration.</li>
<li> <b>extern</b> C function or variable declarations.</li><li>Declarations of C functions defined in the module.</li>
<li> The definition part of an extension type (<a href="#SharingExtensionTypes">see below</a>).</li>
It cannot contain any non-extern C variable declarations.
<p>It cannot contain the implementations of any C or Python functions, or
any Python class definitions, or any executable statements. </p>
<blockquote>NOTE: You don't need to (and shouldn't) declare anything in a
declaration file <b>public</b> in order to make it available to other Pyrex
modules; its mere presence in a definition file does that. You only need a
public declaration if you want to make something available to external C code.</blockquote>
<h3><a class="mozTocH3" name="mozTocId20347"></a> <a name="WhatImpFileContains"></a>What an Implementation File contains</h3>
An implementation file can contain any kind of Pyrex statement, although
there are some restrictions on the implementation part of an extension type
if the corresponding definition file also defines that type (see below).
<h2><a class="mozTocH2" name="mozTocId950993"></a> <a name="CImportStatement"></a>The <tt>cimport</tt> statement</h2>
The <b>cimport</b> statement is used in a definition or implementation
file to gain access to names declared in another definition file. Its syntax
exactly parallels that of the normal Python import statement:
<blockquote><tt>cimport </tt><i>module</i><tt> [, </tt><i>module</i><tt>...]</tt></blockquote>
<blockquote><tt>from </tt><i>module</i><tt> cimport </tt><i>name</i><tt>
[as </tt><i>name</i><tt>] [, </tt><i>name</i><tt> [as </tt><i>name</i><tt>]
Here is an example. The file on the left is a definition file which exports
a C data type. The file on the right is an implementation file which imports
and uses it. <br>
<table cellpadding="5" cols="2" width="100%">
<td bgcolor="#ffcc00" width="40%"><b><tt>dishes.pxd</tt></b></td>
<td bgcolor="#5dbaca"><b><tt>restaurant.pyx</tt></b></td>
<tr align="left" valign="top">
<td bgcolor="#ffcc18" width="40%"><tt>cdef enum otherstuff:</tt> <br>
<tt>&nbsp;&nbsp;&nbsp; sausage, eggs, lettuce</tt>
<p><tt>cdef struct spamdish:</tt> <br>
<tt>&nbsp;&nbsp;&nbsp; int oz_of_spam</tt> <br>
<tt>&nbsp;&nbsp;&nbsp; otherstuff filler</tt></p>
<td bgcolor="#5dbaca"><tt>cimport dishes</tt> <br>
<tt>from dishes cimport spamdish</tt>
<p><tt>cdef void prepare(spamdish *d):</tt> <br>
<tt>&nbsp;&nbsp;&nbsp; d.oz_of_spam = 42</tt> <br>
<tt>&nbsp;&nbsp;&nbsp; d.filler = dishes.sausage</tt> </p>
<p><tt>def serve():</tt> <br>
<tt>&nbsp;&nbsp;&nbsp; cdef spamdish d</tt> <br>
<tt>&nbsp;&nbsp;&nbsp; prepare(&amp;d)</tt> <br>
<tt>&nbsp;&nbsp;&nbsp; print "%d oz spam, filler no. %d" % \</tt>
<tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; (d.oz_of_spam,
<p>It is important to understand that the <b>cimport</b> statement can <i>only</i>
be used to import C data types, C functions and variables, and extension
types. It cannot be used to import any Python objects, and (with one exception)
it doesn't imply any Python import at run time. If you want to refer to any
Python names from a module that you have cimported, you will have to include
a regular <b>import</b> statement for it as well. </p>
<p>The exception is that when you use <b>cimport</b> to import an extension
type, its type object is imported at run time and made available by the
name under which you imported it. Using <b>cimport</b> to import extension
types is covered in more detail <a href="#SharingExtensionTypes">below</a>.
<h3><a class="mozTocH3" name="mozTocId559554"></a> <a name="SearchPaths"></a>Search paths for definition files</h3>
When you <b>cimport</b> a module called <tt>modulename</tt>, the Pyrex
compiler searches for a file called <tt>modulename.pxd</tt> along the search
path for include files, as specified by <b>-I</b> command line options.
<p>Also, whenever you compile a file <tt>modulename.pyx</tt>, the corresponding
definition file <tt>modulename.pxd</tt> is first searched for along the
same path, and if found, it is processed before processing the <tt>.pyx</tt>
file. </p>
<h3><a class="mozTocH3" name="mozTocId478514"></a> <a name="ResolvingNamingConflicts"></a>Using cimport to resolve naming
The cimport mechanism provides a clean and simple way to solve the problem
of wrapping external C functions with Python functions of the same name.
All you need to do is put the extern C declarations into a .pxd file for
an imaginary module, and cimport that module. You can then refer to the C
functions by qualifying them with the name of the module. Here's an example:
<table cellpadding="5" cols="2" width="100%">
<td bgcolor="#ffcc00" width="50%"><b><tt>c_lunch.pxd</tt></b></td>
<td bgcolor="#5dbaca"><b><tt>lunch.pyx</tt></b></td>
<tr align="left" valign="top">
<td bgcolor="#ffcc18" width="50%"><tt>cdef extern from "lunch.h":</tt>
<tt>&nbsp;&nbsp;&nbsp; void eject_tomato(float)</tt></td>
<td bgcolor="#5dbaca"><tt>cimport c_lunch</tt>
<p><tt>def eject_tomato(float speed):</tt> <br>
<tt>&nbsp;&nbsp;&nbsp; c_lunch.eject_tomato(speed)</tt></p>
<p>You don't need any <tt>c_lunch.pyx</tt> file, because the only things
defined in <tt>c_lunch.pxd</tt> are extern C entities. There won't be any
actual <tt>c_lunch</tt> module at run time, but that doesn't matter; the <tt>c_lunch.pxd</tt> file has done its job of providing an additional namespace at compile time.</p><h2><a class="mozTocH2" name="mozTocId937218"></a><a name="Sharing_C_Functions"></a>Sharing C Functions</h2><p>C
functions defined at the top level of a module can be made available
via cimport by putting headers for them in the .pxd file, for example,</p><table style="text-align: left; width: 100%;" border="0" cellpadding="5" cellspacing="2"><tbody><tr><td style="font-weight: bold; background-color: rgb(255, 204, 0);"><pre>volume.pxd</pre></td><td style="font-weight: bold; background-color: rgb(93, 186, 202);"><pre>spammery.pyx</pre></td></tr><tr><td style="vertical-align: top; background-color: rgb(255, 204, 0);"><pre>cdef float cube(float)</pre></td><td style="background-color: rgb(93, 186, 202);" colspan="1" rowspan="3"><pre>from volume cimport cube<br><br>def menu(description, size):<br>&nbsp; &nbsp; print description, ":", cube(size), \<br> "cubic metres of spam"<br><br>menu("Entree", 1)<br>menu("Main course", 3)<br>menu("Dessert", 2)</pre></td></tr><tr style="font-weight: bold;"><td style="vertical-align: top; background-color: rgb(153, 204, 51); height: 1px;"><pre>volume.pyx</pre></td></tr><tr><td style="vertical-align: top; background-color: rgb(153, 204, 51);"><pre>cdef float cube(float x):<br>&nbsp; &nbsp; return x * x * x</pre></td></tr></tbody></table><br><h2><a class="mozTocH2" name="mozTocId825278"></a><a name="Sharing_Extension_Types"></a>Sharing Extension Types</h2>
An extension type can be made available via cimport by splitting its definition into two parts, one in
a definition file and the other in the corresponding implementation file.
The definition part of the extension type can only declare C attributes
and C methods, not Python methods, and it must declare <i>all</i> of that
type's C attributes and C methods.<br>
The implementation part must implement all of the C methods declared in
the definition part, and may not add any further C attributes or methods. It may also
define Python methods.
<p>Here is an example of a module which defines and exports an extension
type, and another module which uses it. <br>
<table cellpadding="5" cols="2" width="100%">
<td bgcolor="#ffcc18" width="30%"><b><tt>Shrubbing.pxd</tt></b></td>
<td bgcolor="#5dbaca" width="50%"><b><tt>Shrubbing.pyx</tt></b></td>
<tr align="left" valign="top">
<td bgcolor="#ffcc18" width="30%"><tt>cdef class Shrubbery:</tt> <br>
<tt>&nbsp;&nbsp;&nbsp; cdef int width</tt> <br>
<tt>&nbsp;&nbsp;&nbsp; cdef int length</tt></td>
<td bgcolor="#5dbaca" width="50%"><tt>cdef class Shrubbery:</tt> <br>
<tt>&nbsp;&nbsp;&nbsp; def __cinit__(self, int w, int l):</tt> <br>
<tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; self.width = w</tt>
<tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; self.length = l</tt>
<p><tt>def standard_shrubbery():</tt> <br>
<tt>&nbsp;&nbsp;&nbsp; return Shrubbery(3, 7)</tt></p>
<td colspan="2" bgcolor="#8cbc1c" width="30%"><b><tt>Landscaping.pyx</tt></b></td>
<td colspan="2" bgcolor="#99cc00" width="30%"><tt>cimport Shrubbing</tt>