Developing C++ Python modules for Cygwin

This tutorial shows how to develop C++ modules that can be loaded into Python scripts under Cygwin. The Cygwin environment contains Windows ports for many Linux-based tools, so if you are porting a Linux application to run on Windows, it can prove time-saving by drastically reducing the porting effort. It also comes with pre-built Python 2.x and 3.x and we will show in this tutorial how to create a module that will be loaded into a Cygwin Python script.

Before you begin, install VisualGDB 5.1 or later and install Cygwin including the following packages:

  • g++
  • gdb
  • make
  • python3
  • python3-debuginfo
  1. Start Visual Studio and launch the VisualGDB MinGW/Cygwin Project Wizard:01-cygpythonprj
  2. Select “Create a new project -> A Cygwin Python module”:02-prjtype
  3. Select the location of your Cygwin toolchain. If it’s not auto-detected, select “specify a Cygwin-based toolchain manually” and point VisualGDB to its location:03-toolchain
  4. On the last page of the wizard replace “python” with “python3″ to explicitly select Python 3.x and press “Finish”:04-python3
  5. VisualGDB will create a project consisting of a C++ Python module, a Makefile building the module using the Python includes and libraries and a simple Python script calling a function from the module. Build the module by pressing Ctrl-Shift-B:05-build
  6. Set a breakpoint in the Python script on the line calling the hello() method and press F5 to start debugging. Once the breakpoint hits you will be able to look through the Python variables or step through the code:06-pydebug
  7. If you step into the hello() method, VisualGDB will actually step into the internal Python function used to call C++ functions, so instead, set a breakpoint in the HelloMethod() and press F5. Once the breakpoint hits, you will see both C++ and Python frames in the Call Stack and will be able to step through the method:07-cppdebug
  8. You can navigate the Call Stack to view the Python code calling the C++ code and even the internal Python interpreter’s functions responsible for handling the calls. This is especially useful when debugging complex memory corruption problems:08-pycall
  9. Set a breakpoint on the print() line and resume debugging. Once the breakpoint is hit, see that the Python script has received the value of 123 returned by the C++ method:09-result