开发者社区> 问答> 正文

使用Boost Python从C ++向python中的类成员变量赋值

我有一个使用Boost python框架公开给python的C ++类。

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)

是否可以x在C ++代码内访问对象并为value成员变量分配一个在c ++中的值,该值在print_func()python脚本中执行时会打印出来?

展开
收起
祖安文状元 2020-02-23 16:14:19 920 0
1 条回答
写回答
取消 提交回答
  • 您可以如下更改python和c ++代码

    /```js /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", initstd::string()) class_ ("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

    2020-02-23 16:14:34
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
From Python Scikit-Learn to Sc 立即下载
Data Pre-Processing in Python: 立即下载
双剑合璧-Python和大数据计算平台的结合 立即下载