#include<boost/python.hpp>#include<boost/python/scope.hpp>#include<boost/python/suite/indexing/vector_indexing_suite.hpp>#include<boost/python/overloads.hpp>#include<vector>#include"module_py.h"
using namespace boost::python;BOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS(write_overloads, MyModulePy::write,2,3);BOOST_PYTHON_MODULE(module_py){
boost::python::scope().attr("__version__")="v20180123.1";
class_<MyModulePy>("MyModulePy").def("read",&MyModulePy::read).def("batch_read",&MyModulePy::batch_read).def("write_read",&MyModulePy::batch_write).def("write",&MyModulePy::write,write_overloads(args("key","value","expire"),"put key-value with a expire time")).def("remove",&MyModulePy::remove).def("config",&MyModulePy::config);}
module_py.h
#include"c_module.h"// header of libmodule.so struct MyModulePy
{MyModulePy(){}
std::string read(const std::string& key){// do read return mModule.Read(key);}
boost::python::dict batch_read(const boost::python::list& keys){
std::vector<std::string>ckeys(boost::python::len(keys));for(int i =0; i < boost::python::len(keys); i++){
ckeys[i]= boost::python::extract<std::string>(keys[i]);}
std::map<std::string, std::string> cvalues = mModule.BatchRead(ckeys);
boost::python::dict values;for(auto it = cvalues.begin(); it != cvalues.end();++it){
values[it->first]= it->second;}return values;}voidbach_write(const boost::python::dict& keyValues){auto skeys = keyValues.keys();// http://www.boost.org/doc/libs/1_34_0/libs/python/doc/v2/dict.htmlint num = boost::python::len(skeys);
std::map<std::string, std::string> datas;for(int i =0; i < num; i++)// TODO: how to iterate a boost::python::dict ? {
string k = boost::python::extract<std::string>(skeys[i]);// NOTE: do not use 'const string& k = '
string v = boost::python::extract<std::string>(subKeyValues[skeys[i]]);
datas[k]= v;}return mModule.batch_write(datas);}voidwrite(const std::string& key,const std::string& value,constint expire =0){// do write
mModule.Write(key, value, expire);}voidremove(const std::string& key){// do remove
mModule.Delete(key);}
std::string config(){return mModule.GetConfigInfo();}
Module mModule;// class provided by libmodule.so };
sample.py
import time
from module_py import MyModulePy
m = MyModulePy()
key ='testkey_%s'% time.time()
value ='testvalue_%s'% time.time()try:print'config:', m.config()
m.write(key, value)
m.write(key, value,10)print'write:', key, value
print'read:', key, m.read(key)print'delete:', key, m.remove(key)for i inxrange(0,3):
mytair.write('batch-%s'% i,str(i))
keys =['batch-%s'% i for i inxrange(0,3)]print mytair.batch_read(keys)for each in keys:
mytair.remove(each)print'read:', key, m.read(key)# exception except Exception, e:print e
/home/admin/pybind11_sample/
|---- py_sample.cpp
|---- sample.py
|---- build.sh
|---- include/
|---- pybind11/ i installed pybind11 at here
|---- text_processor/ c++ module