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

王朝c/c++·作者佚名  2006-01-08
宽屏版  字体: |||超大  

一个简单的例子

假设我们有下面的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日

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
© 2005- 王朝网络 版权所有