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

好久没有写博客了,今天把自己有道云笔记上东西分享给大家。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++函数如果有参数,我们在封装的时候不必指定,只写函数名即可。
  • 返回值如果不是特殊值也不需要特殊指明。
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值