python input函数用法mac_在Mac OSX上从Python脚本调用c ++函数

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"

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值