Tuesday, October 23, 2012

Easy C++ Project for Python Use

For this tutorial, I will be using Visual Studios 2010 (C++) and Python 2.7 with ctypes.

Let's assume your boss wants a program that performs addition, there are many ways to write this code, but for the sake of this this tutorial, you want to use the python and C++.
  • Open Visual Studios
  • Follow the steps in creating a project here.
  • Give the project a name called additioncpp
  • Create a header file called 'additioncpp.h' and enter in the following code:
      int sum(int, int);
  •  In the dllmain.cpp file, comment out everything but the '#include "stdafx.h" line
  • Now we are ready to write the sum() we defined in the additioncpp.h header file.  Since python like 'C', and not 'C++' we need to use exten "C" around the functions
      #include "stdafx.h"
      #define DLLEXPORT extern "C" __declspec(dllexport)

      DLLEXPORT int sum(int a, int b) {
          return a + b;
       }

  • Compile the code and copy the .dll to a new folder
  • Create a new .py file and type in the following:
  • print 'start' 
    from ctypes import cdll
    mydll = cdll.LoadLibrary(r'PATHTODLL\additioncpp.dll')
    print mydll
    print mydll.sum
    print mydll.sum(1,2)
    print 'end'
  • You should see an output like this:
>>> 
>>> <_funcptr 0x10ca47b0="0x10ca47b0" at="at" object="object">
>>> 3
>>> end

Enjoy