利用boost在C++中嵌入python

示列代码

#include <iostream> #include <python2.4/Python.h> #include<boost/python.hpp> using namespace std; using namespace boost::python; int main() { Py_Initialize(); PyRun_SimpleString("from time import time,ctime/n" "print 'Today is',ctime(time())/n"); Py_Finalize(); return 0; }

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

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

 

 

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

//pyinit.hpp #include<boost/noncopyable.hpp> #include<boost/python.hpp> class pyinit: boost::noncopyable { public: pyinit(int initsigs = 1) { assert((initsigs == 1)||(initsigs == 0)); Py_InitializeEx(initsigs); } ~pyinit() { } bool IsInitialized() { return Py_IsInitialized(); } static void err_print() { PyErr_Print(); } const char* version() { return Py_GetVersion(); } };

 

#include <iostream> #include <python2.4/Python.h> #include<boost/python.hpp> #include<string> #include"pyinit.hpp" using namespace std; using namespace boost::python; int main() { pyinit pinit; object s("sa"); string str = extract<string> (s * 5); cout << str << endl; string execstr = "print 'abc'"; try { exec(execstr.c_str()); } catch(...) { pyinit::err_print(); } return 0; }

 

 

 

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

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

 

你可能感兴趣的:(利用boost在C++中嵌入python)