加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

Python 调用 C++

发布时间:2020-12-17 17:08:50 所属栏目:Python 来源:网络整理
导读:今天PHP站长网 52php.cn把收集自互联网的代码分享给大家,仅供参考。 #include boost/python.hpp#include boost/python/module.hpp #include boost/python/def.hpp#include boost/python/to_python_converter.hpp#include

以下代码由PHP站长网 52php.cn收集自互联网

现在PHP站长网小编把它分享给大家,仅供参考

#include <boost/python.hpp>
#include <boost/python/module.hpp>
 
#include <boost/python/def.hpp>
#include <boost/python/to_python_converter.hpp>
#include
using namespace std;
using namespace boost::python;
 
namespace HelloPython{
// 简单函数
char const* sayHello(){
    return "Hello from boost::python";
}
 
 
// 简单类
class HelloClass{
public:
    HelloClass(const string& name):name(name){
    }
public:
    string sayHello(){
      return "Hello from HelloClass by : " + name;
    }
private:
    string name;
};
// 接受该类的简单函数
string sayHelloClass(HelloClass& hello){
    return hello.sayHello() + " in function sayHelloClass";
}
 
 
//STL容器
typedef vector<int> ivector;
 
 
//有默认参数值的函数
void showPerson(string name,int age=30,string nationality="China"){
    cout << name << " " << age << " " << nationality << endl;
}
 
// 封装带有默认参数值的函数
BOOST_PYTHON_FUNCTION_OVERLOADS(showPerson_overloads,showPerson,1,3) //1:最少参数个数,3最大参数个数
 
// 封装模块
BOOST_PYTHON_MODULE(HelloPython){
    // 封装简单函数
    def("sayHello",sayHello);
 
    // 封装简单类,并定义__init__函数
    class_("HelloClass",init())
      .def("sayHello",&HelloClass::sayHello)//Add a regular member function
      ;
    def("sayHelloClass",sayHelloClass); // sayHelloClass can be made a member of module!!!
 
    // STL的简单封装方法
    class_("ivector")
      .def(vector_indexing_suite());
    class_ >("ivector_vector")
      .def(vector_indexing_suite >());
 
    // 带有默认参数值的封装方法
    def("showPerson",showPerson_overloads());
}

以上内容由PHP站长网【52php.cn】收集整理供大家参考研究

如果以上内容对您有帮助,欢迎收藏、点赞、推荐、分享。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读