python调用C和C++代码(BOOST)
2009-02-17 15:31
686 查看
本文使用了Boost中有关Python的部分,并着重介绍如何用C++写的函数或是类,并让Python能调用。先看我们设计好的C++函数和类。
#include <string>
#include <windows.h>
//定义一个函数
void msgbox(const std::string& str)
{
MessageBox(0,str.c_str(),"msgbox",MB_OK);
}
//定义一个C++类
class Hello
{
public:
std::string m_str;
public:
Hello()
{
MessageBox(0,"Called Hello:Hello()","Hello",MB_OK);
}
void SetMsg(const std::string & str)
{
m_str=str;
}
void ShowMsg()
{
MessageBox(0,m_str.c_str(),"Hello",MB_OK);
}
};
要导出成Python能使用的类和函数模块,我们用boost中python模块来实现。
#include <boost/python.hpp>
BOOST_PYTHON_MODULE(pyTest)//这个pyTest即在Python中引用的模块名,用Import导入。并且和Dll的名称需要一模一样才行,扩展名可以由DLL自己保留。
{
using namespace boost::python;
//导出C++类,注意格式,还有里面有init后面,如果构造函数有参数,需要在这里面加入
class_<Hello>("Hello",init<>())
.def("SetMsg",&Hello::SetMsg) //映射成员函数
.def("ShowMsg",&Hello::ShowMsg)//映射成员函数
;
//导出一个C函数,供调用
def("msgbox", msgbox); //映身函数
}
这里,还需要新建一个DLL工程,将这两个源码加入工程,编译成一个DLL。
以下是在Python中调用:
from pyTest import *
megbox('调用C函数,我是DLL中的函数')
h = Hello()
h.SetMsg('我是在脚本中被调用的')
h.ShowMsg()
用IDLE载入,并按F5,就可以执行脚本了。
#include <string>
#include <windows.h>
//定义一个函数
void msgbox(const std::string& str)
{
MessageBox(0,str.c_str(),"msgbox",MB_OK);
}
//定义一个C++类
class Hello
{
public:
std::string m_str;
public:
Hello()
{
MessageBox(0,"Called Hello:Hello()","Hello",MB_OK);
}
void SetMsg(const std::string & str)
{
m_str=str;
}
void ShowMsg()
{
MessageBox(0,m_str.c_str(),"Hello",MB_OK);
}
};
要导出成Python能使用的类和函数模块,我们用boost中python模块来实现。
#include <boost/python.hpp>
BOOST_PYTHON_MODULE(pyTest)//这个pyTest即在Python中引用的模块名,用Import导入。并且和Dll的名称需要一模一样才行,扩展名可以由DLL自己保留。
{
using namespace boost::python;
//导出C++类,注意格式,还有里面有init后面,如果构造函数有参数,需要在这里面加入
class_<Hello>("Hello",init<>())
.def("SetMsg",&Hello::SetMsg) //映射成员函数
.def("ShowMsg",&Hello::ShowMsg)//映射成员函数
;
//导出一个C函数,供调用
def("msgbox", msgbox); //映身函数
}
这里,还需要新建一个DLL工程,将这两个源码加入工程,编译成一个DLL。
以下是在Python中调用:
from pyTest import *
megbox('调用C函数,我是DLL中的函数')
h = Hello()
h.SetMsg('我是在脚本中被调用的')
h.ShowMsg()
用IDLE载入,并按F5,就可以执行脚本了。
相关文章推荐
- 如何在C++代码中调用python代码(MinGW+Boost.Python)
- 如何在C++代码中调用python代码(MinGW+Boost.Python)
- 使用boost.python在python调用C++接口(windows)
- 使用swig在python中调用c++代码
- 用boost封装C++的库供Python调用
- 利用Swig在python中调用C/C++代码
- c++调用Python [boost::python]
- 通过SWIG封装C/C++代码被Python调用
- 【2013】实习收获4:关于python中利用ctypes调用c++代码的学习总结
- python嵌入C++------ boost.python如何在C++中调用含有不定长参数tuple变量和关键字参数dict变量的函数
- Linux下python如何调用c++的代码,用ctypes方法。。
- Windows C++程序调用包含TensorFlow代码的Python脚本出错问题的解决办法
- [转]vs2010用 boost.python 编译c++类库 供python调用
- python 使用Boost.python 调用c++
- C,C++代码中调用python脚本
- linux 下python 调用C++ .so如何debug c++代码
- 使用boost实现python调用c++
- Boost.Python C++与Python的互相调用之Python调用c/c++函数
- 使用boost实现c++与python的相互调用
- 利用Boost.Python将C++代码封装为Python模块