Commit | Line | Data |
---|---|---|
920dae64 AT |
1 | <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> |
2 | <html> | |
3 | <head> | |
4 | <link rel="STYLESHEET" href="ext.css" type='text/css' /> | |
5 | <link rel="SHORTCUT ICON" href="../icons/pyfav.png" type="image/png" /> | |
6 | <link rel='start' href='../index.html' title='Python Documentation Index' /> | |
7 | <link rel="first" href="ext.html" title='Extending and Embedding the Python Interpreter' /> | |
8 | <link rel='contents' href='contents.html' title="Contents" /> | |
9 | <link rel='last' href='about.html' title='About this document...' /> | |
10 | <link rel='help' href='about.html' title='About this document...' /> | |
11 | <link rel="next" href="parseTuple.html" /> | |
12 | <link rel="prev" href="compilation.html" /> | |
13 | <link rel="parent" href="intro.html" /> | |
14 | <link rel="next" href="parseTuple.html" /> | |
15 | <meta name='aesop' content='information' /> | |
16 | <title>1.6 Calling Python Functions from C | |
17 | </title> | |
18 | </head> | |
19 | <body> | |
20 | <DIV CLASS="navigation"> | |
21 | <div id='top-navigation-panel' xml:id='top-navigation-panel'> | |
22 | <table align="center" width="100%" cellpadding="0" cellspacing="2"> | |
23 | <tr> | |
24 | <td class='online-navigation'><a rel="prev" title="1.5 Compilation and Linkage" | |
25 | href="compilation.html"><img src='../icons/previous.png' | |
26 | border='0' height='32' alt='Previous Page' width='32' /></A></td> | |
27 | <td class='online-navigation'><a rel="parent" title="1. Extending Python with" | |
28 | href="intro.html"><img src='../icons/up.png' | |
29 | border='0' height='32' alt='Up One Level' width='32' /></A></td> | |
30 | <td class='online-navigation'><a rel="next" title="1.7 Extracting Parameters in" | |
31 | href="parseTuple.html"><img src='../icons/next.png' | |
32 | border='0' height='32' alt='Next Page' width='32' /></A></td> | |
33 | <td align="center" width="100%">Extending and Embedding the Python Interpreter</td> | |
34 | <td class='online-navigation'><a rel="contents" title="Table of Contents" | |
35 | href="contents.html"><img src='../icons/contents.png' | |
36 | border='0' height='32' alt='Contents' width='32' /></A></td> | |
37 | <td class='online-navigation'><img src='../icons/blank.png' | |
38 | border='0' height='32' alt='' width='32' /></td> | |
39 | <td class='online-navigation'><img src='../icons/blank.png' | |
40 | border='0' height='32' alt='' width='32' /></td> | |
41 | </tr></table> | |
42 | <div class='online-navigation'> | |
43 | <b class="navlabel">Previous:</b> | |
44 | <a class="sectref" rel="prev" href="compilation.html">1.5 Compilation and Linkage</A> | |
45 | <b class="navlabel">Up:</b> | |
46 | <a class="sectref" rel="parent" href="intro.html">1. Extending Python with</A> | |
47 | <b class="navlabel">Next:</b> | |
48 | <a class="sectref" rel="next" href="parseTuple.html">1.7 Extracting Parameters in</A> | |
49 | </div> | |
50 | <hr /></div> | |
51 | </DIV> | |
52 | <!--End of Navigation Panel--> | |
53 | ||
54 | <H1><A NAME="SECTION003600000000000000000"></A><A NAME="callingPython"></A> | |
55 | <BR> | |
56 | 1.6 Calling Python Functions from C | |
57 | ||
58 | </H1> | |
59 | ||
60 | <P> | |
61 | So far we have concentrated on making C functions callable from | |
62 | Python. The reverse is also useful: calling Python functions from C. | |
63 | This is especially the case for libraries that support so-called | |
64 | ``callback'' functions. If a C interface makes use of callbacks, the | |
65 | equivalent Python often needs to provide a callback mechanism to the | |
66 | Python programmer; the implementation will require calling the Python | |
67 | callback functions from a C callback. Other uses are also imaginable. | |
68 | ||
69 | <P> | |
70 | Fortunately, the Python interpreter is easily called recursively, and | |
71 | there is a standard interface to call a Python function. (I won't | |
72 | dwell on how to call the Python parser with a particular string as | |
73 | input -- if you're interested, have a look at the implementation of | |
74 | the <b class="programopt">-c</b> command line option in <span class="file">Python/pythonmain.c</span> | |
75 | from the Python source code.) | |
76 | ||
77 | <P> | |
78 | Calling a Python function is easy. First, the Python program must | |
79 | somehow pass you the Python function object. You should provide a | |
80 | function (or some other interface) to do this. When this function is | |
81 | called, save a pointer to the Python function object (be careful to | |
82 | <tt class="cfunction">Py_INCREF()</tt> it!) in a global variable -- or wherever you | |
83 | see fit. For example, the following function might be part of a module | |
84 | definition: | |
85 | ||
86 | <P> | |
87 | <div class="verbatim"><pre> | |
88 | static PyObject *my_callback = NULL; | |
89 | ||
90 | static PyObject * | |
91 | my_set_callback(PyObject *dummy, PyObject *args) | |
92 | { | |
93 | PyObject *result = NULL; | |
94 | PyObject *temp; | |
95 | ||
96 | if (PyArg_ParseTuple(args, "O:set_callback", &temp)) { | |
97 | if (!PyCallable_Check(temp)) { | |
98 | PyErr_SetString(PyExc_TypeError, "parameter must be callable"); | |
99 | return NULL; | |
100 | } | |
101 | Py_XINCREF(temp); /* Add a reference to new callback */ | |
102 | Py_XDECREF(my_callback); /* Dispose of previous callback */ | |
103 | my_callback = temp; /* Remember new callback */ | |
104 | /* Boilerplate to return "None" */ | |
105 | Py_INCREF(Py_None); | |
106 | result = Py_None; | |
107 | } | |
108 | return result; | |
109 | } | |
110 | </pre></div> | |
111 | ||
112 | <P> | |
113 | This function must be registered with the interpreter using the | |
114 | <tt class="constant">METH_VARARGS</tt> flag; this is described in section | |
115 | <A href="methodTable.html#methodTable">1.4</A>, ``The Module's Method Table and Initialization | |
116 | Function.'' The <tt class="cfunction">PyArg_ParseTuple()</tt> function and its | |
117 | arguments are documented in section <A href="parseTuple.html#parseTuple">1.7</A>, ``Extracting | |
118 | Parameters in Extension Functions.'' | |
119 | ||
120 | <P> | |
121 | The macros <tt class="cfunction">Py_XINCREF()</tt> and <tt class="cfunction">Py_XDECREF()</tt> | |
122 | increment/decrement the reference count of an object and are safe in | |
123 | the presence of <tt class="constant">NULL</tt> pointers (but note that <var>temp</var> will not be | |
124 | <tt class="constant">NULL</tt> in this context). More info on them in | |
125 | section <A href="refcounts.html#refcounts">1.10</A>, ``Reference Counts.'' | |
126 | ||
127 | <P> | |
128 | Later, when it is time to call the function, you call the C function | |
129 | <tt class="cfunction">PyEval_CallObject()</tt>.<a id='l2h-1' xml:id='l2h-1'></a> This | |
130 | function has two arguments, both pointers to arbitrary Python objects: | |
131 | the Python function, and the argument list. The argument list must | |
132 | always be a tuple object, whose length is the number of arguments. To | |
133 | call the Python function with no arguments, pass an empty tuple; to | |
134 | call it with one argument, pass a singleton tuple. | |
135 | <tt class="cfunction">Py_BuildValue()</tt> returns a tuple when its format string | |
136 | consists of zero or more format codes between parentheses. For | |
137 | example: | |
138 | ||
139 | <P> | |
140 | <div class="verbatim"><pre> | |
141 | int arg; | |
142 | PyObject *arglist; | |
143 | PyObject *result; | |
144 | ... | |
145 | arg = 123; | |
146 | ... | |
147 | /* Time to call the callback */ | |
148 | arglist = Py_BuildValue("(i)", arg); | |
149 | result = PyEval_CallObject(my_callback, arglist); | |
150 | Py_DECREF(arglist); | |
151 | </pre></div> | |
152 | ||
153 | <P> | |
154 | <tt class="cfunction">PyEval_CallObject()</tt> returns a Python object pointer: this is | |
155 | the return value of the Python function. <tt class="cfunction">PyEval_CallObject()</tt> is | |
156 | ``reference-count-neutral'' with respect to its arguments. In the | |
157 | example a new tuple was created to serve as the argument list, which | |
158 | is <tt class="cfunction">Py_DECREF()</tt>-ed immediately after the call. | |
159 | ||
160 | <P> | |
161 | The return value of <tt class="cfunction">PyEval_CallObject()</tt> is ``new'': either it | |
162 | is a brand new object, or it is an existing object whose reference | |
163 | count has been incremented. So, unless you want to save it in a | |
164 | global variable, you should somehow <tt class="cfunction">Py_DECREF()</tt> the result, | |
165 | even (especially!) if you are not interested in its value. | |
166 | ||
167 | <P> | |
168 | Before you do this, however, it is important to check that the return | |
169 | value isn't <tt class="constant">NULL</tt>. If it is, the Python function terminated by | |
170 | raising an exception. If the C code that called | |
171 | <tt class="cfunction">PyEval_CallObject()</tt> is called from Python, it should now | |
172 | return an error indication to its Python caller, so the interpreter | |
173 | can print a stack trace, or the calling Python code can handle the | |
174 | exception. If this is not possible or desirable, the exception should | |
175 | be cleared by calling <tt class="cfunction">PyErr_Clear()</tt>. For example: | |
176 | ||
177 | <P> | |
178 | <div class="verbatim"><pre> | |
179 | if (result == NULL) | |
180 | return NULL; /* Pass error back */ | |
181 | ...use result... | |
182 | Py_DECREF(result); | |
183 | </pre></div> | |
184 | ||
185 | <P> | |
186 | Depending on the desired interface to the Python callback function, | |
187 | you may also have to provide an argument list to | |
188 | <tt class="cfunction">PyEval_CallObject()</tt>. In some cases the argument list is | |
189 | also provided by the Python program, through the same interface that | |
190 | specified the callback function. It can then be saved and used in the | |
191 | same manner as the function object. In other cases, you may have to | |
192 | construct a new tuple to pass as the argument list. The simplest way | |
193 | to do this is to call <tt class="cfunction">Py_BuildValue()</tt>. For example, if | |
194 | you want to pass an integral event code, you might use the following | |
195 | code: | |
196 | ||
197 | <P> | |
198 | <div class="verbatim"><pre> | |
199 | PyObject *arglist; | |
200 | ... | |
201 | arglist = Py_BuildValue("(l)", eventcode); | |
202 | result = PyEval_CallObject(my_callback, arglist); | |
203 | Py_DECREF(arglist); | |
204 | if (result == NULL) | |
205 | return NULL; /* Pass error back */ | |
206 | /* Here maybe use the result */ | |
207 | Py_DECREF(result); | |
208 | </pre></div> | |
209 | ||
210 | <P> | |
211 | Note the placement of "<tt class="samp">Py_DECREF(arglist)</tt>" immediately after the | |
212 | call, before the error check! Also note that strictly spoken this | |
213 | code is not complete: <tt class="cfunction">Py_BuildValue()</tt> may run out of | |
214 | memory, and this should be checked. | |
215 | ||
216 | <P> | |
217 | ||
218 | <DIV CLASS="navigation"> | |
219 | <div class='online-navigation'> | |
220 | <p></p><hr /> | |
221 | <table align="center" width="100%" cellpadding="0" cellspacing="2"> | |
222 | <tr> | |
223 | <td class='online-navigation'><a rel="prev" title="1.5 Compilation and Linkage" | |
224 | href="compilation.html"><img src='../icons/previous.png' | |
225 | border='0' height='32' alt='Previous Page' width='32' /></A></td> | |
226 | <td class='online-navigation'><a rel="parent" title="1. Extending Python with" | |
227 | href="intro.html"><img src='../icons/up.png' | |
228 | border='0' height='32' alt='Up One Level' width='32' /></A></td> | |
229 | <td class='online-navigation'><a rel="next" title="1.7 Extracting Parameters in" | |
230 | href="parseTuple.html"><img src='../icons/next.png' | |
231 | border='0' height='32' alt='Next Page' width='32' /></A></td> | |
232 | <td align="center" width="100%">Extending and Embedding the Python Interpreter</td> | |
233 | <td class='online-navigation'><a rel="contents" title="Table of Contents" | |
234 | href="contents.html"><img src='../icons/contents.png' | |
235 | border='0' height='32' alt='Contents' width='32' /></A></td> | |
236 | <td class='online-navigation'><img src='../icons/blank.png' | |
237 | border='0' height='32' alt='' width='32' /></td> | |
238 | <td class='online-navigation'><img src='../icons/blank.png' | |
239 | border='0' height='32' alt='' width='32' /></td> | |
240 | </tr></table> | |
241 | <div class='online-navigation'> | |
242 | <b class="navlabel">Previous:</b> | |
243 | <a class="sectref" rel="prev" href="compilation.html">1.5 Compilation and Linkage</A> | |
244 | <b class="navlabel">Up:</b> | |
245 | <a class="sectref" rel="parent" href="intro.html">1. Extending Python with</A> | |
246 | <b class="navlabel">Next:</b> | |
247 | <a class="sectref" rel="next" href="parseTuple.html">1.7 Extracting Parameters in</A> | |
248 | </div> | |
249 | </div> | |
250 | <hr /> | |
251 | <span class="release-info">Release 2.4.2, documentation updated on 28 September 2005.</span> | |
252 | </DIV> | |
253 | <!--End of Navigation Panel--> | |
254 | <ADDRESS> | |
255 | See <i><a href="about.html">About this document...</a></i> for information on suggesting changes. | |
256 | </ADDRESS> | |
257 | </BODY> | |
258 | </HTML> |