I've a c++ code on my mac that uses non-standard lybraries (in my case, OpenCV libs) and need to compile this so it can be called from other computers (at least from other mac computers). Runned from python. So I've 3 fundamental questions:
How to compile my project so it can be used from python? I've read
that I should create a *.so file but how to do so?
Should it work like a lib, so python calls some specific functions,
chosen in python level?
Or should it contain a main function that is executed from
command line?
Any ideas on how to do so? PS: I'm using the eclipse IDE to compile my c++ project.
Cheers,
解决方案
If you use linux, the answers of atmaere and nouney may work for you.
In my case, as I use MacOSX, I figured my way through using the cython library. A straight forward tutorial to make things work is described bellow:
How to call C++ from Python script:
INSTALL CYTHON: To install Cython, tool that integrates python scripts with c/c++, visit: https://pypi.python.org/pypi/Cython/
PREPARE C++ SOURCE FILES: be sure that your *.cpp and *.h files are correct. In the downloaded example, the filenames are cpp_rect.h and cpp_rect.cpp
CREATE PYTHON WRAPER CPLASS: according to the rectangle.pyx file in the downloaded example or to the model described in http://docs.cython.org/src/userguide/wrapping_CPlusPlus.html?highlight=cpp#create-cython-wrapper-class
PREPARE THE SETUP.PY FILE: the downloaded example already counts with this file but more information can be found in this tutorial: http://docs.cython.org/src/userguide/wrapping_CPlusPlus.html?highlight=cpp#specify-c-language-in-setup-py. [PS: 1 The easiest way to compile is with the disutilis package, using a setup.py file. For mor info about compilation options, visit http://docs.cython.org/src/reference/compilation.html#.
TRY TO COMPILE: Go to the terminal, from the same folder where your source files are. At this point you already ghave 4 files: cpp_rect.h, cpp_rect.cpp, rectangle.pyx and setup.py. From there, execute the command $ python setup.py build_ext --inplace
If you receive a g++ error, such as it happened to me: "unable to execute gcc-4.2: No such file or directory" u can hack the flag system doing sudo ln -s /usr/bin/gcc /usr/bin/gcc-4.2. Than repeat the previous step.
TEST YOUR CODE: At this momment, you have everything you need: the setup.py was used along with the rectangle.pyx to generate the rectangle.so file, which is WHAT we need! Just build a pythons script to test your integration. Luckly, the example already counts with a test script, named use_rect.py.
Now just run it from the terminal using "$ python userect.py"