Saturday 31 August 2013

How To Embed Python PyLab Into A 64bit Windows C Application

Here is a quick solution for embedding PyLab into a 64bit Windows C app. It was a bit fiddly to get setup so after a few trips down blind alleys, here is what I did.

The easiest way to get a Python installation that includes PyLab, Matplotlib, Numpy, Scipy etc is to download Anaconda from : http://www.continuum.io/downloads. In my case I wanted to use the Python v3.3 version under 64 bit Windows. The default Anaconda installation is for v2.x but it is very easy to update to Python v3.3 using conda. form C:\Anaconda type the following command :
conda create -n py33 python=3.3 anaconda

In order to use the v3.3 installation, prepend the following to the PATH environment variable :
C:\Anaconda\envs\py33;C:\Anaconda\envs\py33\Scripts;

Although Anaconda works very well from Python scripts I found that I need to set the following PYTHONPATH environment variable :
set PYTHONPATH=C:\Anaconda\envs\py33;C:\Anaconda\envs\py33\Lib;C:\Anaconda\envs\py33\DLLs

To configure the Visual C compiler for 64 bit mode :
call "C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\vcvarsall.bat" amd64
For further details on installing the 64 bit Microsoft compiler, please see here :
http://realgonegeek.blogspot.co.uk/2013/08/microsoft-visual-c-2010-sdk-v71-64-bit.html

To compile the app use the following command line :
cl example.c -IC:\Anaconda\envs\py33\include C:\Anaconda\envs\py33\libs\python33.lib /link /MACHINE:X64

If you want to try it, here is a quick test program :

#include "Python.h"
int main()
{
Py_Initialize ();
PyRun_SimpleString ("import sys");
PyRun_SimpleString ("import pylab");
PyRun_SimpleString ("print(sys.version)");
PyRun_SimpleString ("print()");
PyRun_SimpleString ("pylab.plot(range(10))");
PyRun_SimpleString ("pylab.show()");
Py_Exit(0);
return 0;
}

If you have found this solution useful then please do hit the Google (+1) button so that others may be able to find it as well.
Numerix-DSP Libraries : http://www.numerix-dsp.com/eval/

No comments:

Post a Comment