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