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