python - 使用boost python从c ++为python中的类成员变量赋值
问题描述
我有一个 C++ 类,它通过 boost python 框架暴露给 python。
struct Var
{
Var(std::string name) : name(name), value() {}
std::string const name;
float value;
};
BOOST_PYTHON_MODULE(hello)
{
class_<Var>("Var", init<std::string>())
.def_readonly("name", &Var::name)
.def_readwrite("value", &Var::value);
;
}
下面是使用这个类的python脚本:
x = hello.Var("hello")
def print_func():
print(x.value)
是否可以访问 C++ 代码中的对象并在 c++ 中为成员变量x
分配一个值,该值在python 脚本中执行时打印出来?value
print_func()
解决方案
您可以更改您的 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
推荐阅读
- java - Java Semaphore 实现和设计相关问题
- python - 为什么不能调用类的属性?
- c# - 将 json 对象反序列化为 C# 对象
- perl - 在获得完整路径后检查其他目录中具有特定类型的动态文件是否存在?
- python - 在 JSON 中附加 OrderedDict
- python - 调用 tkinter 输入框值时,浮点对象不能解释为整数
- google-app-engine - 应用引擎、无服务器容器和 gke 无服务器插件之间的区别
- python - 异常处理建议
- powershell - 在 iis:nanoserver docker 映像上更新 IISAdministration
- bash - scp 从服务器到 lcoal 后找不到交付的文件