Saturday, January 5, 2013

Embedding Python in C++: Hello World

This afternoon I've been "procrastiworking" (working on something that isn't mandatory to postpone doing something mandatory) a bit.
As a result I end up watching this talk by Michael Fötsch:
I just couldn't get to the end of the talk.
When I saw the "Hello world" example, I had to stop the video and try it myself.
This is the code snippet of the experiment:
#include <Python.h>
int main(int argc, char* argv[])
{
  Py_Initialize();
  PyRun_SimpleString(
    "print 'Hello world!'"
  );
  Py_Finalize();
  return 0;
}
This is how I compiled it:
$ g++ -o helloWorld helloWorld.cpp -I/usr/include/python2.6/ -lpython2.6
And this is the result of running it:
$ ./helloWorld
Hello world!
Nice!!
This is just the tip of the iceberg. To learn more about embedding Python in C++ watch Michael's talk.
He also has more advanced material in his blog:
There's also more information in Python's Documentation:
and in this Jun Du's tutorial:
Now you also have material to procrastiwork for a while.
Have fun!

No comments:

Post a Comment