利用Boost在C++中嵌入Python
利用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,结果弄了半天老报错
相关推荐
IT之家 2020-03-11
graseed 2020-10-28
zbkyumlei 2020-10-12
SXIAOYI 2020-09-16
jinhao 2020-09-07
impress 2020-08-26
liuqipao 2020-07-07
淡风wisdon大大 2020-06-06
yoohsummer 2020-06-01
chenjia00 2020-05-29
baike 2020-05-19
扭来不叫牛奶 2020-05-08
hxmilyy 2020-05-11
黎豆子 2020-05-07
xiongweiwei00 2020-04-29
Cypress 2020-04-25
冰蝶 2020-04-20