C++ Boost 之Python(一个简单的例子)

c++boost.gif (8819 bytes)

一个简单的例子

假设我们有下面的C++ API需要暴露给Python:

#include <string>

namespace { // Avoid cluttering the global namespace.

  // A couple of simple C++ functions that we want to expose to Python.
  std::string greet() { return "hello, world"; }
  int square(int number) { return number * number; }
}

这就是要暴露API给Python的getting_started1模块的C++源代码.

#include <boost/python/class_builder.hpp>
namespace python = boost::python;

BOOST_PYTHON_MODULE_INIT(getting_started1)
{
  try
  {
    // Create an object representing this extension module.
    python::module_builder this_module("getting_started1");

    // Add regular functions to the module.
    this_module.def(greet, "greet");
    this_module.def(square, "square");
  }
  catch(...)
  {
    python::handle_exception(); // Deal with the exception for Python
  }
}

成了! 如果我们生成这个共享库并把它放到Python的搜索路径中去, 我们就能在Python中访问这些C++函数了.

>>> import getting_started1
>>> print getting_started1.greet()
hello, world
>>> number = 11
>>> print number, '*', number, '=', getting_started1.square(number)
11 * 11 = 121

Next: 导出类 Previous: 和其他系统的比较 Up: Top

© David Abrahams 2001 版权所有. 本文档允许复制、使用、修改、出售和分发,前提是这个版权声明必须出现在所有的拷贝上。本文档的提供不承担任何直接或隐含的保证,并且不做其适合任一目的之声明。

更新日期: 2000年5月6日

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值