2

I have a demo application that is written in Python. It uses a lot of existing C++ code (written by me) that relies on OpenCV for image processing. Currently, communication between Python and C++ is being done through file I/O and subprocess calls, which isn't very efficient. What is the best way to wrap the C++ code so that it can be called from Python?

There is too much C++ code to think about porting it to Python, so that's not really an option.

A long time ago, the Python OpenCV wrappers were written in SWIG, but it looks like the most recent version of the wrappers is completely different. Can anyone point me in the right direction?

mpenkov
  • 21,621
  • 10
  • 84
  • 126

2 Answers2

1

Without knowing code complexity, variety of C++ code and style of it... I would recommend "Extending Python"

It's not an immediate solution (you should change the C++ code, prototype some new functions or add a simple wrapper layer in C). But, if you plan to do a complex project (and are also a bit worried on performance)... it seems the best way to do it.

Porting C++ code to Python seems a step backwards, doing new code in Python is ok (I'm a fan of it) but C++ will (often) be more efficient.

Edit: Take also a look on ctypes module. Maybe it suits your needs. If you are more comfortable doing the wrapping in python language, then it may be better. If you don't mind playing with the C code, then extend Python by doing a module with your existing code.

MariusSiuram
  • 3,380
  • 1
  • 21
  • 40
1

There are two ways that you can make your python program interact directly with your C/C++ program:

  1. Wrap your C/C++ code in a DLL with C-API only. Then, use ctypes to call C-function within the DLL. The advantage of this way is that you don't need to include/link any other library.

  2. Extend python by adding new python module. You may use boost python to easily create a python module. The advantage of this way is that you don't need to wrap your code to C-API.

Community
  • 1
  • 1
alvinsay
  • 94
  • 1
  • 4
  • I bit the bullet and rewrote the demo in C++ (it was mainly just GUI code). Thanks for your suggestion, though. I'll check out boost python next time I do something like this. – mpenkov Jun 14 '12 at 10:48