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

类别:编程语言 点击:0 评论:0 推荐:
一个简单的例子

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

本文地址:http://com.8s8s.com/it/it29168.htm