其他语言

本类阅读TOP10

·基于Solaris 开发环境的整体构思
·使用AutoMake轻松生成Makefile
·BCB数据库图像保存技术
·GNU中的Makefile
·射频芯片nRF401天线设计的分析
·iframe 的自适应高度
·BCB之Socket通信
·软件企业如何实施CMM
·入门系列--OpenGL最简单的入门
·WIN95中日志钩子(JournalRecord Hook)的使用

分类导航
VC语言Delphi
VB语言ASP
PerlJava
Script数据库
其他语言游戏开发
文件格式网站制作
软件工程.NET开发
C++ Boost 之Python(一个简单的例子)

作者:未知 来源:月光软件站 加入时间:2005-2-28 月光软件站

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日




相关文章

相关软件