Creating Python extensions in C/C++ with SWIG on windows
This is a cookbook for creating Python extensions in C/C++ under Windows with SWIG, distutils and gcc (MinGW version).
I am using to the following versions
1 . SWIG Version 1.3.24
2 . Python 2.3.4
1. Get and install MinGW gcc
Download the compiler from http://www.mingw.org. This GCC compiler runs under Windows and compiled programs do not require support DLL like CygWin GCC.
You only need to download MinGW-1.1.tar.gz (roughly 10,6 Mb). It contains the whole compiler, support utilities, documentation, librairies and header files.
Once decompressed, you should add the \bin directory of MinGW to your path environment variable.
(Example : Under Windows 95/98/ME, if you installed MinGW to c:\gcc, you would add SET PATH=c:\gcc\bin;%PATH% to your AUTOEXEC.BAT.)
If installed properly, you should be able to run gcc –version anywhere. (Mine displays : 2.95.3-6).
2 . Get and install Python
Download the executable from http://www.python.org . As usually set the path to run python from anywhere.
3 . Create libpython23.a
To create Python extensions, you need to link against the Python library. Unfortunately, most Python distributions are provided with Python23.lib, a library in Microsoft Visual C++ format. GCC expects a .a file (libpython23.a to be precise.). Here’s how to convert python23.lib to libpython23.a:
Download pexport (from here or http://starship.python.net/crew/kernr/mingw32/pexports-0.42h.zip).
Get Python23.dll (it should be somewhere on your harddrive).
Run : pexports python23.dll > python23.def
This will extract all symbols from python23.dll and write them into python23.def.
Run : dlltool –dllname python23.dll –def python23.def –output-lib libpython23.a
This will create libpython23.a (dlltool is part of MinGW utilities).
Copy libpython23.a to c:\python23\libs\ (in the same directory as python23.lib).
This trick should work for all Python versions, including future releases of Python. You can also use this trick to convert other libraries.
4. Get and install SWIG
SWIG is a wrapper for C/C++ sources. It allows you to use C/C++ functions and classes to Python with a minimum effort.
Download SWIG binaries for Window ( Swigwin ) from http://www.swig.org, decompress them and add swig directory to your path (the directory where swig.exe is located).
5 . Write .i files
Write the .i files corresponding to your c++ files ( for more on how to write these files visit http://www.swig.org )
6 . Use the following commands to get it going
A . swig –python –c++ example.i
output: example.py & example_wrap.cxx
B. g++ -c *.c++
output: .o files corresponding to your C++
C. g++ -c example_wrap.cxx -Ic:\python23\include
D. g++ -shared *.o -o _example.pyd -Lc:\python23\libs -lpython23
Hopefully this worked . Now you can do an “ import example “ in python .
Filed under: Uncategorized | 4 Comments