C++嵌入python ,通过boost.python

来源:互联网 发布:广联达软件下载4.0 编辑:程序博客网 时间:2024/05/17 01:29

转载自:wyljz vs2010用 boost.python 编译c++类库 供python调用

VS2010建立一个空的DLL

项目属性中配置如下
链接器里的附加库目录加入,python/libs(python的安装目录中),boost/vs2010/lib(生成的boost的目录中)

c/c++的附加库目录加入,boost(boost的下载目录),python/include(python的安装目录)

 

代码文件加入引用

#include <boost/python.hpp>

生成的DLL文件,需改成和导出模块一致的名称,后缀为PYD
将此PYD文件与生成的BOOST/LIB中的boost_python-vc100-mt-1_46_1.dll 一同拷入工作目录,在此目录中新建py文件,就可以 直接 import 模块名,进行使用

 

示例:hello.cpp

[cpp] view plaincopyprint?
  1. #include <iostream>   
  2.   
  3. using namespace std;  
  4.   
  5. class Hello  
  6. {  
  7. public:  
  8.     string hestr;  
  9. private:  
  10.     string title;  
  11. public:  
  12.     Hello(string str){this->title=str;}  
  13.   
  14.     string get(){return this->title;}  
  15. };  

示例:hc.h 继承hello的子类

[cpp] view plaincopyprint?
  1. #pragma once   
  2. #include "hello.cpp"   
  3. class hc:public Hello  
  4. {  
  5. public:  
  6.     hc(string str);  
  7.     ~hc(void);  
  8.   
  9.     int add(int a,int b);  
  10. };  

hc.cpp

[cpp] view plaincopyprint?
  1. #include "hc.h"   
  2.   
  3.   
  4. hc::hc(string str):Hello(str)  
  5. {  
  6.       
  7. }  
  8.   
  9.   
  10. hc::~hc(void)  
  11. {  
  12. }  
  13.   
  14. int hc::add(int a,int b)  
  15. {  
  16.     return a+b;  
  17. }  

导出的类pyhello.cpp

[cpp] view plaincopyprint?
  1. #include "hc.h"   
  2. #include <boost/python.hpp>   
  3.   
  4.   
  5.   
  6. BOOST_PYTHON_MODULE(hello_ext)  
  7. {  
  8.     using namespace boost::python;  
  9.       
  10.     class_<Hello>("Hello",init<std::string>())  
  11.         .def("get",&Hello::get)  
  12.         .def_readwrite("hestr",&Hello::hestr);  
  13.   
  14.     class_<hc,bases<Hello>>("hc",init<std::string>())  
  15.         .def("add",&hc::add);  
  16. }  

 

python项目中调用 dll的目录包含文件:

 

1,boost_python-vc100-mt-1_46_1.dll

2,dll.py  调用dll的py文件

3,hello_ext.pyd  由上述c++生成的dll文件改名而成

 

dll.py内容:

[python] view plaincopyprint?
  1. import hello_ext  
  2. he=hello_ext.Hello("testdddd")  
  3. print he.get()  
  4.   
  5. he.hestr="ggggddd"  
  6. print he.hestr  
  7.   
  8. te=hello_ext.hc("fffff")  
  9. print te.get()  
  10. te.hestr="ddffg"  
  11. print te.hestr  
  12. print te.add(33,44)  
原创粉丝点击