借助Boost在C++中嵌入Python
发布时间:2021-11-25 17:46:13 所属栏目:教程 来源:互联网
导读:利用Boost在C++中嵌入Python示列代码 #include iostream #include python2.4/Python.h #includeboost/python.hpp using namespace std; using namespace boost::python; int main() { Py_Initialize(); PyRun_SimpleString(from time import time,ctime/n pr
利用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,结果弄了半天老报错 ![]() (编辑:开发网_开封站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |