这里学习了
- 重载使用类似于函数指针的概念,让python在调用的时候知道应该调用哪一个函数
void (Example::*d1)() = &Example::doit;
std::string (Example::*d2)(unsigned int) = &Example::doit;
void (Example::*d3)(std::string) = &Example::doit
生成3个函数表示 d1 d2 d3分别表示对应的重载函数
BOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS(fun_,fun,m,n)
def(“fun_name”, fun, fun_())
n:表示最少几个参数
m:表示最多几个参数
实列在c++代码中
#include <sstream>
#include <string>
class Example {
public:
Example()
{}
void doit() { mS = "void"; }
std::string doit(unsigned int i)
{
std::stringstream s;
s << i;
mS = s.str();
return mS;
}
void doit(std::string s) { mS = s; }
int makeIt(std::string s, int n=1, std::string t="")
{
std::stringstream u;
for (unsigned int i=0; i<n; ++i)
u << s;
mS = u.str() + t;
return n + ( t.size() > 0 ? 1 : 0 );
}
std::string print() const { return mS; } //会被python 的print函数 默认调用
private:
std::string mS;
};
#include <boost/python.hpp>
using namespace boost::python;
//一个模板,将makeIt 封装成重载函数,1,3表示最少1个参数,最多3个参数
BOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS(makeIt_overloads, makeIt, 1, 3)
BOOST_PYTHON_MODULE(boost_eg)
{
//这里类似于做一个函数指针的方式,告诉python 如何调用重载函数
void (Example::*d1)() = &Example::doit;
std::string (Example::*d2)(unsigned int) = &Example::doit;
void (Example::*d3)(std::string) = &Example::doit;
class_<Example>("Example")
.def("__str__", &Example::print)
.def("doit", d1)
.def("doit", d2)
.def("doit", d3)
.def("makeIt", &Example::makeIt, makeIt_overloads()) //另一种重载
;
}
python 代码:
#!/usr/bin/env python
from boost_eg import Example
e = Example()
e.doit(); print (e)
print (e.doit(2))
e.doit("Hallo"); print (e)
print ("------")
print (e.makeIt("xxx"), e)
print (e.makeIt("abc", 2), e)
print (e.makeIt("xyz", 3, "abc"), e)
运行结果:
void
2
Hallo
------
1 xxx
2 abcabc
4 xyzxyzxyzabc