安装boost(未尝试只安装 libboost-python-dev)
sudoapt-getinstalllibboost-all-dev
新建hello_ext.cpp,输入以下代码
1charconst *greet() {2return"hello world";3}45 #include <boost/python.hpp>67BOOST_PYTHON_MODULE(hello_ext) {8usingnamespaceboost::python;9 def("greet", greet);10 }
存储,使用以下命令行编译:
g++ -I/usr/include/python2.7-c -fPIC hello_ext.cpp-o hello_ext.o
g++ -shared -o hello_ext.so hello_ext.o -lpython2.7-lboost_python
在hello_ext所在目录,打开 python shell
>>> import hello_ext
>>>PRint hello_ext.greet()
注意事项:
- 要添加 -lpython2.7 和 -lboost_python,否则会出现一个很复杂的函数找不到的问题,参见 http://stackoverflow.com/questions/1771063/no-such-file-or-directory-error-with-boost-python
很好的示例代码: https://github.com/TNG/boost-python-examples