您的位置:首页 > 编程语言 > C语言/C++

c++ python交互之boost.python 简集之类成员变量设置

2011-04-14 18:47 633 查看
将C++类中的私有成员的操作函数设置为Python类中的属性

C++代码:src.cpp
#include <iostream>
#include <string>
using namespace std;

struct Var
{
Var(string name) : name(name), value() {}
string const name;
float value;
};

class A
{
public:
void setname(string str)
{
m_name = str;
}

string getname()
{
return m_name;
}

private:
string m_name;

};

python转换代码:src4py.cpp
#include <boost/python.hpp>
#include "src.cpp"
using namespace boost::python;
BOOST_PYTHON_MODULE(test)
{
class_<Var>("Var", init<std::string>())
.def_readonly("name", &Var::name) //这是固定格式的写法,请注意方法名称
.def_readwrite("value", &Var::value) //这是固定格式的写法,请注意方法名称
;
//add_property 将C++类中的私有成员的操作函数设置为Python类中的属性,第一个为get 第二个为set
class_<A>("A")
.def("setname",&A::setname)
.def("getname",&A::getname)
.add_property("name",&A::getname,&A::setname) //这是固定格式的写法,请注意方法名称
;
}

上述代码编译成so的过程略,详见
http://linkyou.blog.51cto.com/1332494/751815

python调用代码
import test

obj = test.A()
obj.setname("test")
print obj.getname()
print obj.name
obj.name = "haha"
print obj.name
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息