Calling C++ function from python script

Ravi Teja webraviteja at gmail.com
Sat Jan 28 23:48:36 CET 2006


Pankaj wrote:
> The module which i am creating is like
>
> Part A:
> 1. It does some processing by using python code.
> 2. The result of this python code execution is written to a text file.
> [This part is already compelete]]
>
> Part B:
> 1. I read a text file which is outputted by above python script in a
> C++ program
> 2. and again output of this c++ code is text file
> [This part is as well complete with graph data structure construction
> part involved, which i feel can be done in better way in C++ than in
> python]
>
> Now i want to integrate this flow.
>
> The communication between part A and part B is by call to a function
> present in C++
> How should i do that?
> Kindly suggest some ways.
>
> Regards
> Pankaj

If the bulk of your code is in Python, write an extension module in
C++. You can use Swig or Boost here.
If the bulk of your code is in C++, embed Python.
The general rule is "extend, not embed"

Python documentation
http://docs.python.org/ext/ext.html
Unless you know C/C++ well, these are not easy topics.

Boost
http://www.boost.org/libs/python/doc/tutorial/doc/html/index.html
Swig, SIP are other good alternatives.
All the above are relatively easy.

If your C++ can be simplified to C, Pyrex is remarkably easy to write
extensions in. In this case you will import/include a C header
containing your function and write a Pyrex wrapper around it rather
than directly using Pyrex as a language.

If you are on MS Windows, you can always write a COM server in either
language (COM in C++ is not easy unless if you are using something like
C++ Builder).

Or you can simply use popen from Python or use pipes or just read
stdout from either side.

As you can see, there are a number of options.




More information about the Python-list mailing list