python调用C和C++代码(BOOST)

本文使用了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能使用的类和函数模块,我们用boostpython模块来实现。

#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 ,就可以执行脚本了。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值