Boost Python 介绍
来源:互联网 发布:绿坝软件免费下载 编辑:程序博客网 时间:2024/05/01 02:13
http://www.yuanma.org/data/2006/0603/article_598.htm
本文使用了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,就可以执行脚本了。
- Boost Python 介绍
- Boost.Python: 初步介绍
- 【Boost】boost::noncopyable介绍
- 【Boost】boost::function介绍
- 【Boost】boost::dynamic_bitset介绍
- 【Boost】boost::noncopyable介绍
- 【Boost】boost::noncopyable介绍
- 【Boost】boost::function介绍
- 【Boost】boost::function介绍
- 【Boost】boost::function介绍
- 【Boost】boost::noncopyable介绍 .
- 【Boost】boost::bind介绍
- 【Boost】boost::function介绍
- 【Boost】boost::noncopyable介绍
- 【Boost】boost::noncopyable介绍
- Boost】boost::noncopyable介绍
- 【Boost】boost::noncopyable介绍
- Boost介绍
- 文件操作
- 事务具有4个属性
- C++ 扩展和嵌入 Python
- 在 C++ 中使用 Python script
- 拙著《J2ME手机高级编程》新近上架
- Boost Python 介绍
- 使用C/C++扩展Python
- 链接错误nafxcwd.lib(afxmem.obj) : error LNK2005: "void __cdecl operator delete(void *)" (??3@YAXPAX@Z) already defined in libcpd
- Boost python 学习笔记
- VBA中调用Notes
- 电脑保护色
- 使用 Boost.Python 嵌入 Python 模块到 C++
- 关于Oracle SID存在解決辦法
- Notes中用Ajax调用WebService