boost库 python_boost.python库学习

以下学习内容摘录自boost官网

例1. 最简单的HelloWorld例程

#include

// 预备导出的函数

char const* greet()

{

return "hello, world";

}

// 注册PYTHON模块hello_ext

BOOST_PYTHON_MODULE(hello_ext)

{

using namespace boost::python;

//导出函数名与实际函数绑定

def("greet", greet);

}

#编译指令

g++ -shared -O2 helloWorld.cpp \pythonPath\python37.dll -I\pythonPath\include -I \boostPath -L \boostPath\lib -lboost_pytho

n-xxx -o hello_ext.pyd

#Python中调用(注意hello_ext.pyd要在PYTHON的搜索路径下,以及文件名和导出API函数名之间要相同)

import hello_ext

print(hello_ext.greet())

例2. 向PYTHON导出一个结构体

#include

using namespace boost::python;

//World是导出的结构体(所有成员都为公有的类)

struct World

{

void set(std::string msg) { this->msg = msg; }

std::string greet() { return msg; }

std::string msg;

};

//注册PYTHON模块名hello

BOOST_PYTHON_MODULE(hello)

{

//注册PYTHON类World

class_("World")

.def("greet", &World::greet)  //注册类函数

.def("set", &World::set)    //同上

;

}

编译方式同前,调用新模块的示例如下:

>>> import hello

>>> planet = hello.World()

>>> planet.set('howdy')

>>> planet.greet()

'howdy'

例3. 在导出模块的类中加入含参数的非默认初始化函数

#include

using namespace boost::python;

struct World

{

World(std::string msg): msg(msg) {} // added constructor

void set(std::string msg) { this->msg = msg; }

std::string greet() { return msg; }

std::string msg;

};

BOOST_PYTHON_MODULE(hello)

{

class_("World", init<:string>())

.def("greet", &World::greet)

.def("set", &World::set)

;

}

--------------------------------

class_("World", init<:string>())

.def(init())  //假设类的初始化函数有两个双精度浮点参数!

.def("greet", &World::greet)

.def("set", &World::set)

;

例3. 只读/可写 类数据成员导出到PYTHON

#头文件同前

struct Var

{

Var(std::string name) : name(name), value() {}

std::string const name;

float value;

};

class_("Var", init<:string>())

.def_readonly("name", &Var::name)    //只读成员变量

.def_readwrite("value", &Var::value);  //可读写成员变量

例4. PYTHON类成员属性的Boost.Python/C++实现

struct Num

{

Num();

float get() const;

void set(float value);

...

};

class_("Num")

//属性rovalue只读

.add_property("rovalue", &Num::get)

//属性value可读写(读写分别调用类成员函数get/set)

.add_property("value", &Num::get, &Num::set);

标签:set,python,greet,学习,msg,World,boost,hello,def

来源: https://www.cnblogs.com/zbnbu/p/11027741.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值