Calling C++ from Python

Alex Martelli aleaxit at yahoo.com
Fri Aug 17 11:09:55 EDT 2001


"Rbtns" <rbtns082484 at hotmail.com> wrote in message
news:3B7D2A85.A11E46CB at hotmail.com...
> How would I call a C++ object from Python?
>
> I have a file of something like:
>
> #include <iostream.h>
> int main()
> {
>   cout <<"I need this to work\n";
>   return 0;
> }
>
> and I want to display my C++ program output from within a python
> program. Do I create an object of the C++ program, and therefore would
> it need to be in a class?  How do I do this if I don't want the program
> in a class?  How do I import the C++ file?

If you have a complete and stand-alone external program, say foo.exe
on Windows or just foo on Unix, it doesn't matter any more whether it
was originally written in C++ or whatever: you can execute the external
program from Python and get its output.

Say your code above is in executable file C:\pleep\koop.exe.  Your
Python code could just run:
    import os
    koopout = os.popen('c:/pleep/koop.exe').read()
and now variable koopout would refer to a string whose
value is "I need this to work\n".  Note the forward slashes --
you can use backward ones in Python, but it's somewhat
troublesome and forward ones work just fine.

This is simple and very general.  The only problem is, it can be
slow, particularly on Windows where starting another process is
a major issue (not so much of a problem in Linux and other Unix
like operating systems, which start processes more rapidly).

The speed issue only matters if you need to run your external
program often AND each run is pretty lightweight -- the
overhead may be on the order of some tens of milliseconds
(depending on your machine), so if you're only running the
external program a few times OR if each time you run it it
typically has to work for a hundred milliseconds or more, the
overhead of starting the process doesn't really matter.

If it DOES matter in your case, that's where you should start
looking at alternatives, such as writing a Python extension
(you'll need to restructure your C++ so it's not any more a
stand-alone program, of course) or keeping the C++ program
up and having Python interact with it through any of several
possible Inter-Process Communication (IPC) approaches,
including sockets, shared-memory, Corba, COM, XML-RPC,
and others yet.  The latter possibilities also typically require
a lot of restructuring for a C++ program that was originally
designed to stand on its own as a main-program, though.


Alex






More information about the Python-list mailing list