且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-09-22 16:26:11

将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

本文转自elbertchen 51CTO博客,原文链接:http://blog.51cto.com/linkyou/751826,如需转载请自行联系原作者