blob: caac64642ce9168e8723bdcca365c711c0e32672 [file] [log] [blame]
Fred Drakecc8f44b2001-08-20 19:30:29 +00001\chapter{Building C and \Cpp{} Extensions on Windows
2 \label{building-on-windows}}
3
4
5This chapter briefly explains how to create a Windows extension module
Fred Drakec37b65e2001-11-28 07:26:15 +00006for Python using Microsoft Visual \Cpp, and follows with more
Fred Drakecc8f44b2001-08-20 19:30:29 +00007detailed background information on how it works. The explanatory
8material is useful for both the Windows programmer learning to build
9Python extensions and the \UNIX{} programmer interested in producing
10software which can be successfully built on both \UNIX{} and Windows.
11
Martin v. Löwis27761f32002-03-09 10:06:14 +000012Module authors are encouraged to use the distutils approach for
13building extension modules, instead of the one described in this
14section. You will still need the C compiler that was used to build
15Python; typically Microsoft Visual \Cpp.
Fred Drakecc8f44b2001-08-20 19:30:29 +000016
17\section{A Cookbook Approach \label{win-cookbook}}
18
Fred Drake5f293192001-12-13 17:20:32 +000019There are two approaches to building extension modules on Windows,
20just as there are on \UNIX: use the \refmodule{distutils} package to
21control the build process, or do things manually. The distutils
22approach works well for most extensions; documentation on using
23\refmodule{distutils} to build and package extension modules is
24available in \citetitle[../dist/dist.html]{Distributing Python
25Modules}. This section describes the manual approach to building
26Python extensions written in C or \Cpp.
Fred Drakecc8f44b2001-08-20 19:30:29 +000027
Fred Drake5f293192001-12-13 17:20:32 +000028To build extensions using these instructions, you need to have a copy
29of the Python sources of the same version as your installed Python.
30You will need Microsoft Visual \Cpp{} ``Developer Studio''; project
31files are supplied for V\Cpp{} version 6, but you can use older
32versions of V\Cpp. The example files described here are distributed
33with the Python sources in the \file{PC\textbackslash
34example_nt\textbackslash} directory.
Fred Drakecc8f44b2001-08-20 19:30:29 +000035
Fred Drake5f293192001-12-13 17:20:32 +000036\begin{enumerate}
37 \item
38 \strong{Copy the example files}\\
39 The \file{example_nt} directory is a subdirectory of the \file{PC}
40 directory, in order to keep all the PC-specific files under the
41 same directory in the source distribution. However, the
42 \file{example_nt} directory can't actually be used from this
43 location. You first need to copy or move it up one level, so that
44 \file{example_nt} is a sibling of the \file{PC} and \file{Include}
45 directories. Do all your work from within this new location.
Fred Drakecc8f44b2001-08-20 19:30:29 +000046
Fred Drake5f293192001-12-13 17:20:32 +000047 \item
48 \strong{Open the project}\\
49 From V\Cpp, use the \menuselection{File \sub Open Workspace}
50 dialog (not \menuselection{File \sub Open}!). Navigate to and
51 select the file \file{example.dsw}, in the \emph{copy} of the
52 \file{example_nt} directory you made above. Click Open.
Fred Drakecc8f44b2001-08-20 19:30:29 +000053
Fred Drake5f293192001-12-13 17:20:32 +000054 \item
55 \strong{Build the example DLL}\\
56 In order to check that everything is set up right, try building:
Fred Drakecc8f44b2001-08-20 19:30:29 +000057
Fred Drake5f293192001-12-13 17:20:32 +000058 \begin{enumerate}
59 \item
60 Select a configuration. This step is optional. Choose
61 \menuselection{Build \sub Select Active Configuration} and
62 select either ``example - Win32 Release'' or ``example - Win32
63 Debug.'' If you skip this step, V\Cpp{} will use the Debug
64 configuration by default.
Fred Drakecc8f44b2001-08-20 19:30:29 +000065
Fred Drake5f293192001-12-13 17:20:32 +000066 \item
67 Build the DLL. Choose \menuselection{Build \sub Build
68 example_d.dll} in Debug mode, or \menuselection{Build \sub
69 Build example.dll} in Release mode. This creates all
70 intermediate and result files in a subdirectory called either
71 \file{Debug} or \file{Release}, depending on which
72 configuration you selected in the preceding step.
73 \end{enumerate}
74
75 \item
76 \strong{Testing the debug-mode DLL}\\
77 Once the Debug build has succeeded, bring up a DOS box, and change
78 to the \file{example_nt\textbackslash Debug} directory. You
79 should now be able to repeat the following session (\code{C>} is
80 the DOS prompt, \code{>\code{>}>} is the Python prompt; note that
81 build information and various debug output from Python may not
82 match this screen dump exactly):
83
84\begin{verbatim}
85C>..\..\PCbuild\python_d
86Adding parser accelerators ...
87Done.
88Python 2.2 (#28, Dec 19 2001, 23:26:37) [MSC 32 bit (Intel)] on win32
89Type "copyright", "credits" or "license" for more information.
90>>> import example
91[4897 refs]
92>>> example.foo()
93Hello, world
94[4903 refs]
95>>>
96\end{verbatim}
97
98 Congratulations! You've successfully built your first Python
99 extension module.
100
101 \item
102 \strong{Cretating your own project}\\
103 Choose a name and create a directory for it. Copy your C sources
104 into it. Note that the module source file name does not
105 necessarily have to match the module name, but the name of the
106 initialization function should match the module name --- you can
107 only import a module \module{spam} if its initialization function
108 is called \cfunction{initspam()}, and it should call
109 \cfunction{Py_InitModule()} with the string \code{"spam"} as its
110 first argument (use the minimal \file{example.c} in this directory
111 as a guide). By convention, it lives in a file called
112 \file{spam.c} or \file{spammodule.c}. The output file should be
113 called \file{spam.dll} or \file{spam.pyd} (the latter is supported
114 to avoid confusion with a system library \file{spam.dll} to which
115 your module could be a Python interface) in Release mode, or
116 \file{spam_d.dll} or \file{spam_d.pyd} in Debug mode.
117
118 Now your options are:
119
120 \begin{enumerate}
121 \item Copy \file{example.dsw} and \file{example.dsp}, rename
122 them to \file{spam.*}, and edit them by hand, or
123 \item Create a brand new project; instructions are below.
124 \end{enumerate}
125
126 In either case, copy \file{example_nt\textbackslash example.def}
127 to \file{spam\textbackslash spam.def}, and edit the new
128 \file{spam.def} so its second line contains the string
129 `\code{initspam}'. If you created a new project yourself, add the
130 file \file{spam.def} to the project now. (This is an annoying
131 little file with only two lines. An alternative approach is to
132 forget about the \file{.def} file, and add the option
133 \programopt{/export:initspam} somewhere to the Link settings, by
134 manually editing the setting in Project Options dialog).
135
136 \item
137 \strong{Creating a brand new project}\\
138 Use the \menuselection{File \sub New \sub Projects} dialog to
139 create a new Project Workspace. Select ``Win32 Dynamic-Link
140 Library,'' enter the name (\samp{spam}), and make sure the
141 Location is set to the \file{spam} directory you have created
142 (which should be a direct subdirectory of the Python build tree, a
143 sibling of \file{Include} and \file{PC}). Select Win32 as the
144 platform (in my version, this is the only choice). Make sure the
145 Create new workspace radio button is selected. Click OK.
146
147 Now open the \menuselection{Project \sub Settings} dialog. You
148 only need to change a few settings. Make sure All Configurations
149 is selected from the Settings for: dropdown list. Select the
150 C/\Cpp{} tab. Choose the Preprocessor category in the popup menu
151 at the top. Type the following text in the entry box labeled
152 Addditional include directories:
153
154\begin{verbatim}
155..\Include,..\PC
156\end{verbatim}
157
158 Then, choose the Input category in the Link tab, and enter
159
160\begin{verbatim}
161..\PCbuild
162\end{verbatim}
163
164 in the text box labelled ``Additional library path.''
165
166 Now you need to add some mode-specific settings:
167
168 Select ``Win32 Release'' in the ``Settings for'' dropdown list.
169 Click the Link tab, choose the Input Category, and append
170 \code{python22.lib} to the list in the ``Object/library modules''
171 box.
172
173 Select ``Win32 Debug'' in the ``Settings for'' dropdown list, and
174 append \code{python22_d.lib} to the list in the ``Object/library
175 modules'' box. Then click the C/\Cpp{} tab, select ``Code
176 Generation'' from the Category dropdown list, and select ``Debug
177 Multithreaded DLL'' from the ``Use run-time library'' dropdown
178 list.
179
180 Select ``Win32 Release'' again from the ``Settings for'' dropdown
181 list. Select ``Multithreaded DLL'' from the ``Use run-time
182 library:'' dropdown list.
183
184 You should now create the file spam.def as instructed in the
185 previous section. Then chose the \menuselection{Insert \sub Files
186 into Project} dialog. Set the pattern to \code{*.*} and select
187 both \file{spam.c} and \file{spam.def} and click OK. (Inserting
188 them one by one is fine too.)
189\end{enumerate}
190
Fred Drakecc8f44b2001-08-20 19:30:29 +0000191
192If your module creates a new type, you may have trouble with this line:
193
194\begin{verbatim}
195 PyObject_HEAD_INIT(&PyType_Type)
196\end{verbatim}
197
198Change it to:
199
200\begin{verbatim}
201 PyObject_HEAD_INIT(NULL)
202\end{verbatim}
203
204and add the following to the module initialization function:
205
206\begin{verbatim}
207 MyObject_Type.ob_type = &PyType_Type;
208\end{verbatim}
209
210Refer to section 3 of the
211\citetitle[http://www.python.org/doc/FAQ.html]{Python FAQ} for details
212on why you must do this.
213
214
215\section{Differences Between \UNIX{} and Windows
216 \label{dynamic-linking}}
217\sectionauthor{Chris Phoenix}{cphoenix@best.com}
218
219
220\UNIX{} and Windows use completely different paradigms for run-time
221loading of code. Before you try to build a module that can be
222dynamically loaded, be aware of how your system works.
223
Fred Drakec37b65e2001-11-28 07:26:15 +0000224In \UNIX, a shared object (\file{.so}) file contains code to be used by the
Fred Drakecc8f44b2001-08-20 19:30:29 +0000225program, and also the names of functions and data that it expects to
226find in the program. When the file is joined to the program, all
227references to those functions and data in the file's code are changed
228to point to the actual locations in the program where the functions
229and data are placed in memory. This is basically a link operation.
230
231In Windows, a dynamic-link library (\file{.dll}) file has no dangling
232references. Instead, an access to functions or data goes through a
233lookup table. So the DLL code does not have to be fixed up at runtime
234to refer to the program's memory; instead, the code already uses the
235DLL's lookup table, and the lookup table is modified at runtime to
236point to the functions and data.
237
Fred Drakec37b65e2001-11-28 07:26:15 +0000238In \UNIX, there is only one type of library file (\file{.a}) which
Fred Drakecc8f44b2001-08-20 19:30:29 +0000239contains code from several object files (\file{.o}). During the link
240step to create a shared object file (\file{.so}), the linker may find
241that it doesn't know where an identifier is defined. The linker will
242look for it in the object files in the libraries; if it finds it, it
243will include all the code from that object file.
244
245In Windows, there are two types of library, a static library and an
246import library (both called \file{.lib}). A static library is like a
247\UNIX{} \file{.a} file; it contains code to be included as necessary.
248An import library is basically used only to reassure the linker that a
249certain identifier is legal, and will be present in the program when
250the DLL is loaded. So the linker uses the information from the
251import library to build the lookup table for using identifiers that
252are not included in the DLL. When an application or a DLL is linked,
253an import library may be generated, which will need to be used for all
254future DLLs that depend on the symbols in the application or DLL.
255
256Suppose you are building two dynamic-load modules, B and C, which should
Fred Drakec37b65e2001-11-28 07:26:15 +0000257share another block of code A. On \UNIX, you would \emph{not} pass
Fred Drakecc8f44b2001-08-20 19:30:29 +0000258\file{A.a} to the linker for \file{B.so} and \file{C.so}; that would
259cause it to be included twice, so that B and C would each have their
260own copy. In Windows, building \file{A.dll} will also build
261\file{A.lib}. You \emph{do} pass \file{A.lib} to the linker for B and
262C. \file{A.lib} does not contain code; it just contains information
263which will be used at runtime to access A's code.
264
265In Windows, using an import library is sort of like using \samp{import
266spam}; it gives you access to spam's names, but does not create a
Fred Drakec37b65e2001-11-28 07:26:15 +0000267separate copy. On \UNIX, linking with a library is more like
Fred Drakecc8f44b2001-08-20 19:30:29 +0000268\samp{from spam import *}; it does create a separate copy.
269
270
271\section{Using DLLs in Practice \label{win-dlls}}
272\sectionauthor{Chris Phoenix}{cphoenix@best.com}
273
Fred Drakec37b65e2001-11-28 07:26:15 +0000274Windows Python is built in Microsoft Visual \Cpp; using other
Fred Drakecc8f44b2001-08-20 19:30:29 +0000275compilers may or may not work (though Borland seems to). The rest of
276this section is MSV\Cpp{} specific.
277
278When creating DLLs in Windows, you must pass \file{python15.lib} to
279the linker. To build two DLLs, spam and ni (which uses C functions
280found in spam), you could use these commands:
281
282\begin{verbatim}
283cl /LD /I/python/include spam.c ../libs/python15.lib
284cl /LD /I/python/include ni.c spam.lib ../libs/python15.lib
285\end{verbatim}
286
287The first command created three files: \file{spam.obj},
288\file{spam.dll} and \file{spam.lib}. \file{Spam.dll} does not contain
289any Python functions (such as \cfunction{PyArg_ParseTuple()}), but it
290does know how to find the Python code thanks to \file{python15.lib}.
291
292The second command created \file{ni.dll} (and \file{.obj} and
293\file{.lib}), which knows how to find the necessary functions from
294spam, and also from the Python executable.
295
296Not every identifier is exported to the lookup table. If you want any
297other modules (including Python) to be able to see your identifiers,
298you have to say \samp{_declspec(dllexport)}, as in \samp{void
299_declspec(dllexport) initspam(void)} or \samp{PyObject
300_declspec(dllexport) *NiGetSpamData(void)}.
301
302Developer Studio will throw in a lot of import libraries that you do
303not really need, adding about 100K to your executable. To get rid of
304them, use the Project Settings dialog, Link tab, to specify
305\emph{ignore default libraries}. Add the correct
306\file{msvcrt\var{xx}.lib} to the list of libraries.