目录
一、Hello word
-
安装boost
boost版本:BOOST-1.67
修改boost/python/detail/config.hpp中的bug
//#define BOOST_LIB_NAME boost_python##PY_MAJOR_VERSION##PY_MINOR_VERSION #define _BOOST_PYTHON_CONCAT(N, M, m) N ## M ## m #define BOOST_PYTHON_CONCAT(N, M, m) _BOOST_PYTHON_CONCAT(N, M, m) #define BOOST_LIB_NAME BOOST_PYTHON_CONCAT(boost_python, PY_MAJOR_VERSION, PY_MINOR_VERSION)
-
创建hello.cpp
#define BOOST_PYTHON_STATIC_LIB #include <boost/python/module.hpp> #include <boost/python/def.hpp> char const* greet() { return "hello, world"; } BOOST_PYTHON_MODULE(hello_ext) { using namespace boost::python; def("greet", greet); }
-
编译好的dll改名为hello_ext.pyd
-
在python文件中引用
import hello_ext print(hello_ext.greet())
-
运行python
二、包装类对象
#include <string>
using namespace std;
#define BOOST_PYTHON_STATIC_LIB
struct World
{
World(std::string msg) :msg(msg) {}
void set(std::string msg) { this->msg = msg; }
std::string greet() { return msg; }
std::string msg;
};
struct Var {
Var(std::string name) :name(name), value() {}
std::string const name;
float value;
};
struct Num {
private:
float value;
public:
float get() const {
return value;
};
void set(float value) {
this->value = value;
}
};
#include <boost/python.hpp>
using namespace boost::python;
BOOST_PYTHON_MODULE(hello)
{
class_<World>("World", init<std::string>())
.def("greet", &World::greet)
.def("set", &World::set);
class_<Var>("Var", init<std::string>())
.def_readonly("name", &Var::name)
.def_readwrite("value", &Var::value);
class_<Num>("Num")
.add_property("rovalue", &Num::get)
.add_property("value", &Num::get, &Num::set);
};
下面分别导出了World、Var、Num三个类,并且演示了如何导出类中的方法和属性。