您可以更改您的 python 和 c++ 代码,如下所示
//I hope you are expecting some functionality like below
class Var
{
public:
Var(std::string name) : name(name), value() {}
std::string const name;
double value;
void set_value();
double get_value();
};
Var::set_value(double value)
{
this->value = value;
}
double Var::get_value(){
return this->value;
}
// c++ Var class constructor caller
Var* var_constructor_caller(string name){
return new Var(name);
}
BOOST_PYTHON_MODULE(hello_ext)
{
//class_<Var>("Var", init<std::string>())
class_<Valr>("Var") // this line is for c++ class not exposed to python
.def("set_value", &Var::set_value)
.def("get_value", &Var::get_value)
.def_readonly("name", &Var::name)
.def_readwrite("value", &Var::value);
;
def("var_constructor_caller", var_constructor_caller, return_value_policy<manage_new_object>());
// by <manage_new_object> return type you are giving owner ship to python to delete the object
}
下面是使用这个类的python脚本:
import hello_ext as hello
var_obj = hello.var_constructor_caller("myname")
var_obj.set_value(3.14)
value = var_obj.get_value()
print value
var_object.value = 5.75 #you call directly assign value also to c++ class data member
print value