利用Boost在C++中嵌入Python


利用Boost在C++中嵌入Python示列代码

  1. #include <iostream>  
  2. #include <python2.4/Python.h>  
  3. #include<boost/python.hpp>   
  4.   
  5. using namespace std;  
  6. using namespace boost::python;  
  7.   
  8. int main() {  
  9.   
  10.     Py_Initialize();  
  11.     PyRun_SimpleString("from time import time,ctime/n"  
  12.     "print 'Today is',ctime(time())/n");  
  13.     Py_Finalize();  
  14.     return 0;  
  15. }  

编译时在连接选项中加入-I python2.4

目前环境是CentOS5.5,python为自带安装的2.4版本 

按照boost开发指南上封装Python对象

  1. //pyinit.hpp   
  2. #include<boost/noncopyable.hpp>   
  3. #include<boost/python.hpp>   
  4.   
  5. class pyinit: boost::noncopyable {  
  6. public:  
  7.     pyinit(int initsigs = 1) {  
  8.         assert((initsigs == 1)||(initsigs == 0));  
  9.         Py_InitializeEx(initsigs);  
  10.     }  
  11.     ~pyinit() {  
  12.     }  
  13.     bool IsInitialized() {  
  14.         return Py_IsInitialized();  
  15.     }  
  16.     static void err_print() {  
  17.         PyErr_Print();  
  18.     }  
  19.     const char* version() {  
  20.         return Py_GetVersion();  
  21.     }  
  22. };   

 

  1. #include <iostream>   
  2. #include <python2.4/Python.h>   
  3. #include<boost/python.hpp>   
  4. #include<string>   
  5. #include"pyinit.hpp"   
  6.   
  7. using namespace std;  
  8. using namespace boost::python;  
  9.   
  10. int main() {  
  11.     pyinit pinit;  
  12.     object s("sa");  
  13.     string str = extract<string> (s * 5);  
  14.     cout << str << endl;  
  15.     string execstr = "print 'abc'";  
  16.     try {  
  17.         exec(execstr.c_str());  
  18.     }  
  19.     catch(...) {  
  20.         pyinit::err_print();  
  21.     }  
  22.     return 0;  
  23. }   

编译:g++  -o"test111"  ./src/test111.o   -lpython2.4 -lboost_python

由于开始没有加上-lboost_python,结果弄了半天老报错

相关内容