CARVIEW |
Select Language
HTTP/2 200
date: Fri, 18 Jul 2025 11:55:53 GMT
server: Apache/2.4.41 (Ubuntu)
vary: Cookie,User-Agent,Accept-Encoding
set-cookie: MOIN_SESSION_443_ROOT_moin=b7c381bade3f5057a9a17c8fd61272b081eb58a6; Expires=Fri, 18-Jul-2025 12:55:00 GMT; Max-Age=3600; Secure; Path=/
content-encoding: gzip
content-type: text/html; charset=utf-8
x-clacks-overhead: GNU Terry Pratchett
strict-transport-security: max-age=315360000; includeSubDomains; preload
boost.python/SimpleExample - Python Wiki
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.hpp> using namespace boost::python; BOOST_PYTHON_MODULE(getting_started1) { // Add regular functions to the module. def("greet", greet); def("square", square); }
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
boost.python/SimpleExample (last edited 2008-11-15 14:00:37 by localhost)
Unable to edit the page? See the FrontPage for instructions.