Integrate Python in a C/C++ application

Alex Martelli aleax at aleax.it
Fri May 16 10:34:49 EDT 2003


<posted & mailed>

Jacky Buyck wrote:

> Hi all.
>     I'm studying solution to embed scripting langage in C/C++ application.
> I'll not learn you anything if I say you that giving to an application the
> power of scripting you give it a more longer life.
>     FOr the moment I've mainly focused my attention around Lua and Ruby.
>     But
> I want to know if I can do the same with Python ? In Lua it's really
> simpe. In Ruby I'ven't make any test for the moment. I know that some game
> use Python for their scripting langage so I want to know if it's simple to
> control the logic of an application using Python ?

Yes, *embedding* the Python interpreter inside your C or C++ application
is indeed quite feasible and not too hard (I vaguely remember from back
when I played with Lua that it may be even simpler there -- but with Python
you get far more power, so the tradeoff may still be worthwhile).  The
Python online docs come with good coverage of this issue and the Python
source distribution includes among its Demos some that are about this
embedding concept.

Incidentally, Bertrand Meyer (even though the language he invented,
Eiffel, is SO drastically different from Python, Ruby etc) had it right
when he claimed that "a real system has no top".  If your application
is a collection of reusable components (orchestrated into some kind of
control flow by thin and simple 'main programs'), then you need not
worry about 'embedding' at all -- you just make your reusable components
available to Python as "python extensions" (modules, packages) and you
lead a vastly more charmed life -- you just recode the 'thin and simple
main programs' in Python and away you go, with zillions of very useful
possibilities that mere "embedding" doesn't make easy (e.g. using your
application's functionality in webpages and the like).

Unfortunately, if you do have a somewhat monolithic application which
insists on controlling its logic-flow, it's not easy in general to turn
it into a vastly-more-useful collection of reusable components, therefore
'embedding' still has a niche, even though it's somewhat of a crutch.  But
keep the issue in mind when you design your NEXT application: *real systems
have no top* -- make sure EVERY functionally relevant tidbits lives in a
fully-reusable component, and the 'main programs' are mere skeletons that
can be recoded at will with minimal effort.


Alex





More information about the Python-list mailing list