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

Boost-python封装Cpp代码供Python调用

2018-01-13 18:18 344 查看
好久没有写博客了,今天把自己有道云笔记上东西分享给大家。Boost::python的使用可以参考我的一篇博客,这里只列举几个简单的例子,对该篇博客的补充。

封装一个单一的函数

#include<iostream>

#include<boost/python/def.hpp>
#include<boost/python/module.hpp>
#include<boost/python/args.hpp>
#include<pyconfig.h>

using namespace boost::python;
using namespace std;

void HelloWorld(){
cout << "HelloWorld!" << endl;
}

BOOST_PYTHON_MODULE(CToPython){
def("hello", HelloWorld, "Print HelloWorld!");
}


带参数的单一函数

void HelloWorld(string out,string put){
cout << out+put << endl;
}

BOOST_PYTHON_MODULE(CToPython){
def("hello", HelloWorld,args("x","y"), "Print HelloWorld!");
}


注意:

BOOST_PYTHON_MODULE(***)中的***必须和工程项目名称相同。

args参数,是C++函数的形参名映射到python函数的形参名,也就是说C++函数HelloWorld(string out,string put)最终映射到python中是hello(x,y)

封装一个类

#include<iostream>

#include<boost/python/def.hpp>
#include<boost/python/module.hpp>
#include<boost/python/args.hpp>
#include<boost/python/class.hpp>
#include<pyconfig.h>

using namespace boost::python;
using namespace std;

class helloworld{
public:
string name;
string talk;
public:
helloworld(){
name = "hua";
talk = "HelloWorld!";
}
helloworld(string n, string t){
name = n;
talk = t;
}
void set_name(string n){
name = n;
}
void set_talk(string t){
talk = t;
}
string get_name(){
return name;
}
string get_talk(){
return talk;
}
};
BOOST_PYTHON_MODULE(CToPython){
class_<helloworld>("helloworld", init<>())
.def(init<string,string>())
.def_readonly("name", &helloworld::name)
//.def_readwrite("name",&helloworld::name)
.def_readwrite("talk", &helloworld::talk)
.def("set_name",&helloworld::set_name)
.def("set_talk",&helloworld::set_talk)
.def("get_name",&helloworld::get_name)
.def("get_talk",&helloworld::get_talk)
;
}


注意:

在封装类的时候一定要加上头文件

#include<boost/python/class.hpp>


对于默认的构造函数,如果没有参数则使用
int<>()
;如果有参数
init<string,string>()
只说明参数类型即可;

我们也可以直接封装类的成员变量,但是要注意成员变量必须是公有的,我们可以通过指定访问限制,来保护成员变量:
def_readonly()
只能读不能写,
def_readwrite()
可读可写;

C++函数如果有参数,我们在封装的时候不必指定,只写函数名即可。

返回值如果不是特殊值也不需要特殊指明。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python cpp