c++ python交互之boost.python 简集之类(class , struct)

<p>本章描述c++类,如何被python识别和使用</p>
<p><strong>c++代码:src.cpp</strong>
</p>
<p></p>
<p>#include <iostream><br>
#include <string><br>
using namespace std;<br><br>
/**********************************************struct and class ***********************************/<br>
struct A<br>
{<br>
void greet()<br>
{<br>
cout << "just a test! from A" << endl;<br>
}<br><br>
};<br><br>
struct B<br>
{<br>
B(string msg): msg(msg) {}<br><br>
void set(string msg)<br>
{ <br>
this->msg = msg;<br>
}<br><br>
void greet()<br>
{<br>
cout << msg << endl;<br>
}<br><br>
string msg;<br>
};<br><br>
class C<br>
{<br>
public:<br>
void greet()<br>
{<br>
cout << "just a test! from C" << endl;<br>
}<br><br>
};</p>
<p></p>
<p><strong>pyhton转换代码</strong>
:src4py.cpp</p>
<p>#include <boost/python.hpp><br>
#include "src.cpp"<br>
using namespace boost::python;<br>
BOOST_PYTHON_MODULE(test)<br>
{<br>
class_<A>("A")<br>
.def("greet", &A::greet)<br>
;<br><br><strong>class_<B>("B",init<string>())</strong>
//注意构造函数的写法<br>
.def("greet", &B::greet)<br>
.def("set", &B::set)<br>
;<br><br>
class_<C>("C")<br>
.def("greet", &C::greet)<br>
;<br><br>
//Constructors overload<br>
class_<D>("D",init<string,int>())<br>
.def(init<string>())<br>
.def("printstr",&D::printstr)<br>
.def("printint",&D::printint)<br>
;<br><br>
//if we do not wish to expose any constructors in E at all<br>
class_<E>("E",no_init)<br>
.def("printstr",&E::printstr)<br>
;<br>
class_<F>("F")<br>
.def("initE",&F::initE)<br>
.def("printEstr",&F::printEstr)<br>
;<br>
}</p>
<p>编译成so过程省略,如果要看makefile文件,请参照第一篇文章</p>
<p><a href="http://blog.csdn.net/linkyou/archive/2011/04/14/6323940.aspx">http://blog.csdn.net/linkyou/archive/2011/04/14/6323940.aspx</a>
</p>
<p></p>
<p><strong>python中调用代码</strong>
test.py</p>
<p>import test<br><br>
obj = test.A() //对应c++的struct A<br>
obj.greet() //structA中的方法greet<br><br>
obj = test.B("just a test! from B") //对应c++的struct B,且含构造函数<br>
obj.greet()<br>
obj.set("test again! from B")<br>
obj.greet()<br><br>
obj = test.C()<br>
obj.greet()<br><br>
obj = test.D("just a test!",1)<br>
obj.printstr()<br>
obj.printint()<br><br>
#if we do not wish to expose any constructors in E at all<br>
obj = test.F()<br>
e = obj.initE("just a test!")<br>
e.printstr()<br>
obj.printEstr() <br><br></p>
<p></p>
<p></p>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值