使用boost.python实现python调用c++代码
编写c++代码后,编译成动态链接库,然后python可以直接调用
参考http://www.boost.org/doc/libs/1_61_0/libs/python/doc/html/index.html
代码中实现了python参数,到c++参数的转化,可以把一个python的可迭代对象转化成c++中的list map vector等
就像python基础教程上写的,python开发中最完美的就是关键代码用c++,这样兼具性能和开发效率!!
下面是c++代码:
#include
#include
#include
#include
#include
#include
using namespace std;
bool align(string a, string b) {
vector left;
vector right;
string spChar(",\t ");
vector splitResult;
boost::split(splitResult, a, boost::is_any_of(spChar));
BOOST_FOREACH(std::string& s, splitResult) {
boost::trim(s);
left.push_back(boost::lexical_cast(s));
cout << left[ left.size()-1 ]<< endl;
}
splitResult.clear();
boost::split(splitResult, b, boost::is_any_of(spChar));
BOOST_FOREACH(std::string& s, splitResult) {
boost::trim(s);
right.push_back(boost::lexical_cast(s));
cout << right[ right.size()-1 ] << endl;
}
return true;
}
void pythonIterable2Vec( boost::python::object o, vector &vec) {
try {
boost::python::object iter_obj = boost::python::object( boost::python::handle<>( PyObject_GetIter( o.ptr() ) ) );
while( 1 ) {
boost::python::object obj = boost::python::extract( iter_obj.attr( "next" )() ); // Should always work
int val = boost::python::extract( obj ); // Should launch an exception if you wannot extract an int ...
vec.push_back(val);
cout << val << endl;
}
}
catch( ... ) {
PyErr_Clear(); // If there is an exception (no iterator, extract failed or end of the list reached), clear it and exit the function
return;
}
}
bool alignVector(boost::python::object l, boost::python::object r) {
vector left;
vector right;
pythonIterable2Vec(l, left);
pythonIterable2Vec(r, right);
return true;
}
BOOST_PYTHON_MODULE(test)
{
using namespace boost::python;
def("align", align);
def("alignVector", alignVector);
}
编译命令:
g++ -std=c++11 -fPIC test.cpp -o test.so -shared -I/usr/include/python2.7 -lboost_python
python使用:
>>> import test
>>> dir(test)
['__doc__', '__file__', '__name__', '__package__', 'align', 'alignVector']
>>> test.align("1,2,3", "4,6,5")
1
2
3
4
6
5
True
>>> test.alignVector([1,3,2], [4,5,6])
1
3
2
4
5
6
True
>>> a = {1,3,4}
>>> b = {2,3,4}
>>> a
set([1, 3, 4])
>>> b
set([2, 3, 4])
>>> test.alignVector(a, b)
1
3
4
2
3
4
True
>>>