#

# A Simple Example

Suppose we have the following C++ API which we want to expose in 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; }
>     }

Here is the C++ code for a python module called `getting_started1` which exposes the API.

>     #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
>       }
>     }

That's it! If we build this shared library and put it on our `PYTHONPATH` we can now access our C++ functions from Python.

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

> Next: Exporting Classes Previous: Comparisons with other systems Up: Top

> © Copyright David Abrahams 2000. Permission to copy, use, modify, sell and distribute this document is granted provided this copyright notice appears in all copies. This document is provided "as is" without express or implied warranty, and with no claim as to its suitability for any purpose.

> Updated: Mar 6, 2000