这个是c++ 的代码
#include <boost/python.hpp>
#include <boost/python/list.hpp>
#include <boost/python/extract.hpp>
#include <string>
#include <sstream>
#include <vector>
struct World
{
void set(std::string msg) { mMsg = msg; }
void many(boost::python::list msgs) {
long l = len(msgs);
std::stringstream ss;
for (long i = 0; i<l; ++i) {
if (i>0) ss << ", ";
std::string s = boost::python::extract<std::string>(msgs[i]);
ss << s;
}
mMsg = ss.str();
}
std::string greet() { return mMsg; }
std::string mMsg;
};
using namespace boost::python; //这里必须写
BOOST_PYTHON_MODULE(boost_eg)
{
class_<World>("World") //导入一个默认构造函数的,类
.def("greet", &World::greet)//导入类中的greet函数
.def("set", &World::set)//导入类中的set函数
.def("many", &World::many)//导入类的many函数
;//一个导入语句结束,加分号结束
};
python调用的代码
import boost_eg
t = boost_eg.World()
t.set("bom dia!")
print (t.greet())
t.many(['Good Morning', 'Buon giorno', 'Kali mera'])
print (t.greet())
运行结果
bom dia!
Good Morning, Buon giorno, Kali mera