安裝boost(未嘗試只安裝 libboost-python-dev)
sudo apt-get install libboost-all-dev
新建hello_ext.cpp,輸入以下代碼
 1 char const *greet() { 2   return "hello world"; 3 } 4  5 #include <boost/python.hpp> 6  7 BOOST_PYTHON_MODULE(hello_ext) { 8   using namespace boost::python; 9   def("greet", greet);10 }存儲,使用以下命令行編譯:
g++ -I/usr/include/python2.7 -c -fPIC hello_ext.cpp -o hello_ext.og++ -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
新聞熱點
疑難解答