### Boost.Python C++ Example: Embedding and Executing Python Source: https://www.boost.org/doc/libs/latest/libs/python/doc/html/reference/embedding This C++ example demonstrates using Boost.Python's `import` and `exec` functions to define a Python function and then call it from C++. It shows how to retrieve Python objects, execute code, and extract results back into C++. ```cpp #include #include using namespace boost::python; void greet() { // Retrieve the main module. object main = import("__main__"); // Retrieve the main module's namespace object global(main.attr("__dict__")); // Define greet function in Python. object result = exec( "def greet(): \n" " return 'Hello from Python!' \n", global, global); // Create a reference to it. object greet = global["greet"]; // Call it. std::string message = extract(greet()); std::cout << message << std::endl; } ``` -------------------------------- ### Boost.Python Extension Class Example Source: https://www.boost.org/doc/libs/latest/libs/python/doc/html/reference/high_level_components/boost_python_init_hpp Demonstrates how to use `boost::python::init` to expose C++ constructors to Python. This example shows mapping `X` class constructors with different signatures and includes docstrings and call policies. ```cpp using namespace boost::python; class_("X", "This is X's docstring.", init(args("x","y"), "X.__init__'s docstring")[ with_custodian_and_ward<1,3>()] ) .def(init()) ; ``` -------------------------------- ### Configure Multiple Python Builds (Debug/Release) on Windows Source: https://www.boost.org/doc/libs/latest/libs/python/doc/html/building/configuring_boost_build This example demonstrates how to configure Boost.Build to recognize both standard and debug builds of Python installed from source on Windows. It specifies paths for both the release and debug Python executables and includes conditions to differentiate them. ```jam using python : 2.5 : C:\src\Python-2.5\PCBuild\python ; using python : 2.5 : C:\src\Python-2.5\PCBuild\python_d \ : # includes : # libs : on ; ``` -------------------------------- ### Install Python Framework on Mac OS X Source: https://www.boost.org/doc/libs/latest/libs/python/doc/html/faq/does_boost_python_work_with_mac_ Instructions for installing Python 2.3 as a framework on Mac OS X 10.2.8 using the provided commands. This is necessary for Boost.Python compatibility and requires root privileges for the final installation step. ```shell ./configure --enable-framework make make frameworkinstall ``` -------------------------------- ### Python Iteration Protocol Example Source: https://www.boost.org/doc/libs/latest/libs/python/doc/html/tutorial/tutorial/iterators Demonstrates the typical iteration protocol in Python, involving getting an iterator and repeatedly calling `.next()` until a `StopIteration` exception is raised. ```python iter = x.__iter__() # get iterator try: while 1: y = iter.next() # get each item ... # process y except StopIteration: pass # iterator exhausted ``` -------------------------------- ### Boost.Python Example: Registering From-Python and To-Python Converters Source: https://www.boost.org/doc/libs/latest/libs/python/doc/html/reference/function_invocation_and_creation/function_documentation This C++ example shows how to register converters for types `A` and `B` using `expected_from_python_type` and `to_python_target_type`. It defines custom conversion logic for `B` to and from Python, and exposes a function `func`. ```cpp #include #include #include #include #include using namespace boost::python; struct A { }; struct B { A a; B(const A& a_):a(a_){} }; // Converter from A to python int struct BToPython #if defined BOOST_PYTHON_SUPPORTS_PY_SIGNATURES //unnecessary overhead if py signatures are not supported : converter::to_python_target_type //inherits get_pytype #endif { static PyObject* convert(const B& b) { return incref(object(b.a).ptr()); } }; // Conversion from python int to A struct BFromPython { BFromPython() { boost::python::converter::registry::push_back ( &convertible , &construct , type_id< B >() #if defined BOOST_PYTHON_SUPPORTS_PY_SIGNATURES //invalid if py signatures are not supported , &converter::expected_from_python_type::get_pytype//convertible to A can be converted to B #endif ); } static void* convertible(PyObject* obj_ptr) { extract ex(obj_ptr); if (!ex.check()) return 0; return obj_ptr; } static void construct( PyObject* obj_ptr, converter::rvalue_from_python_stage1_data* data) { void* storage = ( (converter::rvalue_from_python_storage< B >*)data)-> storage.bytes; extract ex(obj_ptr); new (storage) B(ex()); data->convertible = storage; } }; B func(const B& b) { return b ; } BOOST_PYTHON_MODULE(pytype_function_ext) { to_python_converter< B , BToPython #if defined BOOST_PYTHON_SUPPORTS_PY_SIGNATURES //invalid if py signatures are not supported ,true #endif >(); //has get_pytype BFromPython(); class_("A") ; def("func", &func); } ``` -------------------------------- ### Compile-time Docstring Options Example (C++/Python) Source: https://www.boost.org/doc/libs/latest/libs/python/doc/html/reference/high_level_components/boost_python_docstring_options_h Illustrates how to configure docstring options at compile time using `docstring_options` and a preprocessor macro. The example shows the resulting Python docstring when `DEMO_DOCSTRING_SHOW_ALL` is set to true or false. ```cpp #include #include #include void foo() {} BOOST_PYTHON_MODULE(demo) { using namespace boost::python; docstring_options doc_options(DEMO_DOCSTRING_SHOW_ALL); def("foo", foo, "foo doc"); } ``` ```python # If compiled with -DDEMO_DOCSTRING_SHOW_ALL=true: # >>> import demo # >>> print demo.foo.__doc__ # foo() -> None : foo doc # C++ signature: # foo(void) -> void # If compiled with -DDEMO_DOCSTRING_SHOW_ALL=false: # >>> import demo # >>> print demo.foo.__doc__ # None ``` -------------------------------- ### enum_ Usage Example Source: https://www.boost.org/doc/libs/latest/libs/python/doc/html/reference/high_level_components/boost_python_enum_hpp Complete example demonstrating how to expose a C++ enumeration to Python using the enum_ class template, including value assignment and value export. ```APIDOC ## enum_ Usage Example ### C++ Module Definition ```cpp #include #include #include using namespace boost::python; enum color { red = 1, green = 2, blue = 4 }; color identity_(color x) { return x; } BOOST_PYTHON_MODULE(enums) { enum_("color") .value("red", red) .value("green", green) .export_values() .value("blue", blue) ; def("identity", identity_); } ``` ### Python Usage Examples ```python >>> from enums import * # Using exported values (red and green are exported) >>> identity(red) enums.color.red >>> identity(green) enums.color.green # Using enum type with non-exported value >>> identity(color.blue) enums.color.blue # Non-exported values not accessible directly >>> identity(blue) NameError: name 'blue' is not defined # Creating enum instances by value >>> identity(color(1)) enums.color.red >>> identity(color(4)) enums.color.blue # Invalid type raises TypeError >>> identity(1) TypeError: bad argument type for built-in operation ``` ### Key Points - Values added before export_values() are exported to the current scope - Values added after export_values() are only accessible via the enum type (color.blue) - Enum instances can be created by value using the enum type as a callable - Direct integer arguments are not accepted; must use enum type or exported values ``` -------------------------------- ### Boost.Python Example: Choosing and Calling C++ Functions Source: https://www.boost.org/doc/libs/latest/libs/python/doc/html/reference/function_invocation_and_creation/boost_python_make_function_hpp This C++ example demonstrates how to use `boost::python::make_function` to create Python-callable wrappers for C++ functions. The `choose_function` C++ function returns a Python object that, when called, executes either the `foo` or `bar` C++ function based on a boolean argument. This illustrates dynamic function wrapping and Python module definition with Boost.Python. ```C++ #include #include char const* foo() { return "foo"; } char const* bar() { return "bar"; } using namespace boost::python; object choose_function(bool selector) { if (selector) return boost::python::make_function(foo); else return boost::python::make_function(bar); } BOOST_PYTHON_MODULE(make_function_test) { def("choose_function", choose_function); } ``` -------------------------------- ### Configure Windows and Cygwin Python Installations Source: https://www.boost.org/doc/libs/latest/libs/python/doc/html/building/configuring_boost_build This configuration illustrates how to set up Boost.Build for both native Windows Python and a Cygwin Python installation. It specifies the Python executable path for Cygwin and uses the 'cygwin' condition to distinguish it, enabling cross-platform builds. ```jam # windows installation using python ; # cygwin installation using python : : c:\cygwin\bin\python2.5 : : : cygwin ; ``` -------------------------------- ### Boost.Python Example: Overloaded Functions and Methods Source: https://www.boost.org/doc/libs/latest/libs/python/doc/html/reference/function_invocation_and_creation/boost_python_overloads_hpp A complete C++ example demonstrating the usage of boost/python/overloads.hpp to expose overloaded C++ functions and member functions to Python. It includes definitions for free functions, class members, and their corresponding Boost.Python module definitions with overloaded interfaces. ```C++ #include #include #include #include #include #include #include using namespace boost::python; tuple f(int x = 1, double y = 4.25, char const* z = "wow") { return make_tuple(x, y, z); } BOOST_PYTHON_FUNCTION_OVERLOADS(f_overloads, f, 0, 3) struct Y {}; struct X { Y& f(int x, double y = 4.25, char const* z = "wow") { return inner; } Y inner; }; BOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS(f_member_overloads, f, 1, 3) BOOST_PYTHON_MODULE(args_ext) { def("f", f, f_overloads( args("x", "y", "z"), "This is f's docstring" )); class_("Y") ; class_("X", "This is X's docstring") .def("f1", &X::f, f_member_overloads( args("x", "y", "z"), "f's docstring" )[return_internal_reference<>()] ) ; } ``` -------------------------------- ### Example: Creating a tuple from sequence elements Source: https://www.boost.org/doc/libs/latest/libs/python/doc/html/reference/object_wrappers/boost_python_tuple_hpp A C++ function demonstrating the use of `boost::python::make_tuple` to create a new Python tuple containing the first and last elements of an input sequence. ```cpp using namespace boost::python; tuple head_and_tail(object sequence) { return make_tuple(sequence[0],sequence[-1]); } ``` -------------------------------- ### Boost.Python Example: Implicit Conversions in C++ Source: https://www.boost.org/doc/libs/latest/libs/python/doc/html/reference/to_from_python_type_conversion/boost_python_implicit_hpp This C++ example demonstrates how to use `boost::python::implicitly_convertible` to enable implicit conversions between a custom C++ class `X` and `int`. It shows how to expose functions and classes to Python and register bidirectional implicit conversions. ```cpp #include #include #include using namespace boost::python; struct X { X(int x) : v(x) {} operator int() const { return v; } int v; }; int x_value(X const& x) { return x.v; } X make_x(int n) { return X(n); } BOOST_PYTHON_MODULE(implicit_ext) { def("x_value", x_value); def("make_x", make_x); class_("X", init()) ; implicitly_convertible(); implicitly_convertible(); } ``` -------------------------------- ### Boost.Python pointer_holder Example (C++) Source: https://www.boost.org/doc/libs/latest/libs/python/doc/html/reference/utility_and_infrastructure/boost_python_instance_holder_hpp A C++ template example demonstrating a concrete derived class `pointer_holder` from `instance_holder`. This class is used by Boost.Python to wrap classes held by smart pointers, providing necessary constructors and the `holds` implementation. ```cpp template struct pointer_holder : instance_holder { // construct from the SmartPtr type pointer_holder(SmartPtr p) :m_p(p) // Forwarding constructors for the held type pointer_holder(PyObject*) :m_p(new Value()) { } template pointer_holder(PyObject*,A0 a0) :m_p(new Value(a0)) { } template pointer_holder(PyObject*,A0 a0,A1 a1) :m_p(new Value(a0,a1)) { } ... private: // required holder implementation void* holds(type_info dst_t) { // holds an instance of the SmartPtr type... if (dst_t == python::type_id()) return &this->m_p; // ...and an instance of the SmartPtr's element_type, if the // pointer is non-null return python::type_id() == dst_t ? &*this->m_p : 0; } private: // data members SmartPtr m_p; }; ``` -------------------------------- ### Boost.Python NumPy binary_ufunc Usage Example Source: https://www.boost.org/doc/libs/latest/libs/python/doc/html/numpy/reference/binary_ufunc Provides a complete C++ example demonstrating the usage of `binary_ufunc` with Boost.Python and NumPy. It defines a `BinarySquare` functor and exposes it to Python as a class named 'BinarySquare', enabling its use with NumPy arrays. ```cpp namespace p = boost::python; namespace np = boost::python::numpy; struct BinarySquare { typedef double first_argument_type; typedef double second_argument_type; typedef double result_type; double operator()(double a,double b) const { return (a*a + b*b) ; } }; p::object ud = p::class_ >("BinarySquare").def("__call__", np::binary_ufunc::make()); p::object inst = ud(); result_array = inst.attr("__call__")(demo_array,demo_array) ; std::cout << "Square of list with binary ufunc is " << p::extract (p::str(result_array)) << std::endl ; ``` -------------------------------- ### Boost.Python raw_function Example: C++ Implementation Source: https://www.boost.org/doc/libs/latest/libs/python/doc/html/reference/function_invocation_and_creation/boost_python_raw_function_hpp This C++ code demonstrates how to use raw_function to expose a C++ function 'raw' to Python. The 'raw' function accepts a tuple and a dictionary, which are then returned as a tuple. ```cpp #include #include #include #include #include using namespace boost::python; tuple raw(tuple args, dict kw) { return make_tuple(args, kw); } BOOST_PYTHON_MODULE(raw_test) { def("raw", raw_function(raw)); } ``` -------------------------------- ### Boost.Python raw_function Example: Python Usage Source: https://www.boost.org/doc/libs/latest/libs/python/doc/html/reference/function_invocation_and_creation/boost_python_raw_function_hpp This Python code shows how to call the C++ function exposed via raw_function. It demonstrates passing both positional and keyword arguments, which are then processed by the C++ function. ```python >>> from raw_test import * >>> raw(3, 4, foo = 'bar', baz = 42) ((3, 4), {'foo': 'bar', 'baz': 42}) ``` -------------------------------- ### Conditional Python Toolset Configuration Source: https://www.boost.org/doc/libs/latest/libs/python/doc/html/building/configuring_boost_build This example demonstrates how to configure Python for a specific toolset using the 'condition' parameter. This is useful when you have a separate Python build intended for use with a particular toolset, while a default configuration is used for most other toolsets. ```jam using python ; # use for most toolsets # Example for a specific toolset (e.g., 'mytoolset') - condition parameter not shown in original text, but implied by context # using python : : mytoolset ; ``` -------------------------------- ### Build Boost.Python Module with bjam Source: https://www.boost.org/doc/libs/latest/libs/python/doc/html/tutorial/tutorial/hello This command initiates the build process for the Boost.Python 'Hello World' example using bjam. It navigates to the tutorial directory and executes the build. The output shows the compilation and linking stages, concluding with successful test execution. ```bash cd C:\dev\boost\libs\python\example\tutorial bjam ...patience... ...found 1101 targets... ...updating 35 targets... Creating library _path-to-boost_python.dll_ Creating library /path-to-hello_ext.exp/ **passed** ... hello.test ...updated 35 targets... ``` -------------------------------- ### Minimalist Jamroot for Boost.Python Source: https://www.boost.org/doc/libs/latest/libs/python/doc/html/tutorial/tutorial/hello A sample Jamroot file for building Boost.Python modules. It includes essential directives for setting up the project and dependencies. Users need to adjust the 'use-project boost' line to point to their Boost root directory. ```jam project : common on *.cpp : $(BOOST_ROOT)/include -I$(BOOST_ROOT)/include -L$(BOOST_ROOT)/lib boost ; ``` -------------------------------- ### C++: Example of Exposing Data Members with Boost.Python Source: https://www.boost.org/doc/libs/latest/libs/python/doc/html/reference/function_invocation_and_creation/boost_python_data_members_hpp An example demonstrating how to use `make_getter` and `make_setter` with Boost.Python to expose a C++ class's data member (`y` in struct `X`) as callable Python functions (`get` and `set`). This allows Python code to interact with C++ data members. ```cpp #include #include #include struct X { X(int x) : y(x) {} int y; }; using namespace boost::python; BOOST_PYTHON_MODULE_INIT(data_members_example) { class_("X", init()) .def("get", make_getter(&X::y)) .def("set", make_setter(&X::y)) ; } ``` -------------------------------- ### Python: Injecting __getinitargs__ for Pickling Source: https://www.boost.org/doc/libs/latest/libs/python/doc/html/reference/topics/pickle_support This Python code demonstrates a lightweight alternative for implementing pickle support by injecting the '__getinitargs__' method into a Boost.Python wrapped class. This allows instances to be pickled by providing the necessary arguments for reconstruction via __init__. ```python # import the wrapped world class from pickle4_ext import world # definition of __getinitargs__ def world_getinitargs(self): return (self.get_country(),) # now inject __getinitargs__ (Python is a dynamic language!) world.__getinitargs__ = world_getinitargs ``` -------------------------------- ### Create Wrapped Class Instances with Boost.Python class_ Source: https://www.boost.org/doc/libs/latest/libs/python/doc/html/tutorial/tutorial/object Shows how to use Boost.Python's `class_` template to wrap C++ classes and create instances with initialization parameters. The example demonstrates wrapping a Vec2 class, defining read-only properties, and instantiating wrapped objects with specific constructor arguments. ```C++ object vec345 = ( class_("Vec2", init()) .def_readonly("length", &Point::length) .def_readonly("angle", &Point::angle) )(3.0, 4.0); assert(vec345.attr("length") == 5.0); ``` -------------------------------- ### Create slice with start and stop parameters in Boost.Python Source: https://www.boost.org/doc/libs/latest/libs/python/doc/html/reference/object_wrappers/boost_python_slice_hpp Constructs a slice with provided start and stop values and a default step value. Requires start and stop to be of type slice_nil or convertible to object. Equivalent to the Python built-in slice(start, stop) or base[start:stop] expression. Throws error_already_set if conversion to object fails. ```cpp template slice(Int1 start, Int2 stop); ``` -------------------------------- ### Expose C++ Class Properties (Getters/Setters) to Python with Boost.Python Source: https://www.boost.org/doc/libs/latest/libs/python/doc/html/tutorial/tutorial/exposing This snippet demonstrates exposing C++ class properties to Python using Boost.Python's `add_property`. It shows how to create read-only properties by providing only a getter function and read-write properties by providing both getter and setter functions. The example uses a 'Num' class with 'get' and 'set' methods. ```C++ struct Num { Num(); float get() const; void set(float value); ... }; #include using namespace boost::python; BOOST_PYTHON_MODULE(hello) { class_("Num") .add_property("rovalue", &Num::get) .add_property("value", &Num::get, &Num::set) ; } ``` ```Python >>> x = Num() >>> x.value = 3.14 >>> x.value, x.rovalue (3.14, 3.14) >>> x.rovalue = 2.17 # error! ``` -------------------------------- ### Python Example: Inspecting Boost.Python Exposed Functions and Classes Source: https://www.boost.org/doc/libs/latest/libs/python/doc/html/reference/function_invocation_and_creation/function_documentation Shows the output of Python's `help()` function when used on a module exposed via Boost.Python. This demonstrates how the generated docstrings, including C++ signatures and argument details, are presented to the Python user. ```python >>> import args_ext >>> help(args_ext) Help on module args_ext: NAME args_ext FILE args_ext.pyd CLASSES Boost.Python.instance(__builtin__.object) X class X(Boost.Python.instance) | This is X's docstring | | Method resolution order: | X | Boost.Python.instance | __builtin__.object | | Methods defined here: | | __init__(...) | __init__( (object)self) -> None : | C++ signature: | void __init__(struct _object *) | | f(...) | f( (X)self, (int)x, (float)y, (str)z) -> tuple : This is X.f's docstring | C++ signature: | class boost::python::tuple f(struct X {lvalue},int,double,char const *) | | ................. | FUNCTIONS f(...) f([ (int)x=1 [, (float)y=4.25 [, (str)z='wow']]]) -> tuple : This is f's docstring C++ signature: class boost::python::tuple f([ int=1 [,double=4.25 [,char const *='wow']]]) f1(...) f1([ (int)x [, (float)y [, (str)z]]]) -> tuple : f1's docstring C++ signature: class boost::python::tuple f1([ int [,double [,char const *]]]) raw(...) object raw(tuple args, dict kwds) : C++ signature: object raw(tuple args, dict kwds) ``` -------------------------------- ### Create slice with start, stop, and step parameters in Boost.Python Source: https://www.boost.org/doc/libs/latest/libs/python/doc/html/reference/object_wrappers/boost_python_slice_hpp Constructs a slice with start, stop, and step values. Requires all three parameters to be of type slice_nil or convertible to object. Equivalent to the Python built-in slice(start, stop, step) or base[start:stop:step] expression. Throws error_already_set if conversion to object fails. ```cpp template slice(Int1 start, Int2 stop, Int3 step); ``` -------------------------------- ### Include Headers and Setup Namespaces for Boost.Python NumPy Source: https://www.boost.org/doc/libs/latest/libs/python/doc/html/numpy/tutorial/simple Includes necessary Boost.Python NumPy headers and establishes namespace aliases for cleaner code syntax. This is the first step required before using any numpy array functionality in Boost.Python. ```cpp #include #include namespace p = boost::python; namespace np = boost::python::numpy; ``` -------------------------------- ### Boost.Python docstring_options Constructors (C++) Source: https://www.boost.org/doc/libs/latest/libs/python/doc/html/reference/high_level_components/boost_python_docstring_options_h Demonstrates the different constructors for the `docstring_options` class. These constructors allow initialization with options to show all docstrings and signatures, a combination of user-defined docstrings and signatures, or separate control over user-defined, Python signatures, and C++ signatures. ```cpp docstring_options(bool show_all=true); docstring_options(bool show_user_defined, bool show_signatures); docstring_options(bool show_user_defined, bool show_py_signatures, bool show_cpp_signatures); ``` -------------------------------- ### Boost.Python return_value_policy Example Source: https://www.boost.org/doc/libs/latest/libs/python/doc/html/reference/function_invocation_and_creation/models_of_callpolicies An example demonstrating how return_value_policy inherits from default_call_policies. It utilizes a custom result_converter (Handler) while retaining the default precall and postcall behavior. ```C++ template struct return_value_policy : Base { typedef Handler result_converter; }; ``` -------------------------------- ### Exposing C++ Function using Python C API Source: https://www.boost.org/doc/libs/latest/libs/python/doc/html/article This snippet shows how to expose the C++ 'greet' function to Python using the raw Python C API. It involves manual argument parsing (PyArg_ParseTuple), result conversion (PyString_FromString), and module definition (PyMethodDef, Py_InitModule). It highlights the verbosity and potential pitfalls like unhandled exceptions and incorrect type conversions. ```c extern "C" // all Python interactions use 'C' linkage and calling convention { // Wrapper to handle argument/result conversion and checking PyObject* greet_wrap(PyObject* args, PyObject * keywords) { int x; if (PyArg_ParseTuple(args, "i", &x)) // extract/check arguments { char const* result = greet(x); // invoke wrapped function return PyString_FromString(result); // convert result to Python } return 0; // error occurred } // Table of wrapped functions to be exposed by the module static PyMethodDef methods[] = { { "greet", greet_wrap, METH_VARARGS, "return one of 3 parts of a greeting" } , { NULL, NULL, 0, NULL } // sentinel }; // module initialization function DL_EXPORT init_hello() { (void) Py_InitModule("hello", methods); // add the methods to the module } } ``` -------------------------------- ### Boost.Python has_back_reference Example (C++) Source: https://www.boost.org/doc/libs/latest/libs/python/doc/html/reference/utility_and_infrastructure An example demonstrating the specialization of `has_back_reference` for a C++ class `X` to indicate it holds a `PyObject*`. This example also shows the creation of C++ classes `X` and `Y` and their registration with Boost.Python modules. The `X` class, after specialization, will receive a 'back reference' to its Python object, while `Y` will not, affecting how instances are handled when passed between Python and C++. ```cpp #include #include #include #include #include using namespace boost::python; using boost::shared_ptr; struct X { X(PyObject* self) : m_self(self), m_x(0) {} X(PyObject* self, int x) : m_self(self), m_x(x) {} X(PyObject* self, X const& other) : m_self(self), m_x(other.m_x) {} handle<> self() { return handle<>(borrowed(m_self)); } int get() { return m_x; } void set(int x) { m_x = x; } PyObject* m_self; int m_x; }; // specialize has_back_reference for X namespace boost { namespace python { template <> struct has_back_reference : mpl::true_ {}; }} struct Y { Y() : m_x(0) {} Y(int x) : m_x(x) {} int get() { return m_x; } void set(int x) { m_x = x; } int m_x; }; shared_ptr Y_self(shared_ptr self) { return self; } BOOST_PYTHON_MODULE(back_references) { class_("X") .def(init()) .def("self", &X::self) .def("get", &X::get) .def("set", &X::set) ; class_ >("Y") .def(init()) .def("get", &Y::get) .def("set", &Y::set) .def("self", Y_self) ; } ``` -------------------------------- ### Configure bjam for MSVC and Python (Windows) Source: https://www.boost.org/doc/libs/latest/libs/python/doc/html/tutorial/tutorial/hello This configuration file sets up bjam to use the Microsoft Visual C++ 8.0 compiler and specifies the location of a Python 2.4 installation. This is crucial for building Boost.Python modules on Windows when custom compiler or Python paths are needed. ```jam # MSVC configuration using msvc : 8.0 ; # Python configuration using python : 2.4 : C:_dev/tools/Python_ ; ``` -------------------------------- ### Expose C++ greet() function to Python using Boost.Python Source: https://www.boost.org/doc/libs/latest/libs/python/doc/html/tutorial/index This C++ code snippet demonstrates how to expose a simple C++ function 'greet' to Python using the Boost.Python library. It includes the necessary Boost.Python header and uses the BOOST_PYTHON_MODULE macro to define the Python extension module. The 'def' function is used to register the C++ function with Python. This allows the 'greet' function to be called directly from Python after the shared library is imported. ```cpp char const* greet() { return "hello, world"; } ``` ```cpp #include BOOST_PYTHON_MODULE(hello_ext) { using namespace boost::python; def("greet", greet); } ``` -------------------------------- ### Boost.Python make_reference_holder Example Source: https://www.boost.org/doc/libs/latest/libs/python/doc/html/reference/function_invocation_and_creation/models_of_resultconverter An example of a MakeHolder policy for to_python_indirect. This struct defines how to create an instance_holder for a C++ object, specifically a pointer_holder in this case, allowing for reference-like behavior in Python. ```cpp struct make_reference_holder { typedef boost::python::objects::instance_holder* result_type; template static result_type execute(T* p) { return new boost::python::objects::pointer_holder(p); } }; struct reference_existing_object { // metafunction returning the ResultConverter template struct apply { typedef boost::python::to_python_indirect type; }; }; ``` -------------------------------- ### Boost.Python `return_internal_reference` Implementation Example Source: https://www.boost.org/doc/libs/latest/libs/python/doc/html/reference/function_invocation_and_creation/models_of_callpolicies Shows how `with_custodian_and_ward_postcall` is used to implement `return_internal_reference`. This example demonstrates creating a type that returns a reference to an internal object, ensuring its lifetime is managed by another argument. ```cpp template struct return_internal_reference : with_custodian_and_ward_postcall<0, owner_arg, Base> { typedef reference_existing_object result_converter; }; ``` -------------------------------- ### Boost.Python noddy_cache Module Example Source: https://www.boost.org/doc/libs/latest/libs/python/doc/html/reference/to_from_python_type_conversion/boost_python_lvalue_from_pytype_ This C++ example demonstrates using `lvalue_from_pytype` with `extract_identity` to create a Python module that caches a specific C++ object. It involves defining C++ functions and registering them with Boost.Python. ```cpp #include #include #include #include // definition lifted from the Python docs typedef struct { PyObject_HEAD } noddy_NoddyObject; using namespace boost::python; static handle cache; bool is_cached(noddy_NoddyObject* x) { return x == cache.get(); } void set_cache(noddy_NoddyObject* x) { cache = handle(borrowed(x)); } BOOST_PYTHON_MODULE(noddy_cache) { def("is_cached", is_cached); def("set_cache", set_cache); // register Noddy lvalue converter lvalue_from_pytype,&noddy_NoddyType>(); } ``` -------------------------------- ### Boost.Python instance_holder install Modifier (C++) Source: https://www.boost.org/doc/libs/latest/libs/python/doc/html/reference/utility_and_infrastructure/boost_python_instance_holder_hpp The `install` method of the `instance_holder` class in Boost.Python. This function attaches a new C++ instance holder to the head of a Python object's chain of held instances. ```cpp void install(PyObject* inst) throw(); ``` -------------------------------- ### Boost.Python Default Argument Handling (Manual Wrappers) Source: https://www.boost.org/doc/libs/latest/libs/python/doc/html/tutorial/tutorial/functions Illustrates a manual approach to wrapping C++ functions with default arguments using 'thin wrappers'. Separate C++ functions are created for each desired argument signature, which are then exposed to Python using Boost.Python's `def`. ```C++ // write "thin wrappers" int f1(int x) { return f(x); } int f2(int x, double y) { return f(x,y); } /*...*/ // in module init def("f", f); // all arguments def("f", f2); // two arguments def("f", f1); // one argument ``` -------------------------------- ### Add Source Files in Jamroot Source: https://www.boost.org/doc/libs/latest/libs/python/doc/html/building/no_install_quickstart Demonstrates how to include additional source files (`file1.cpp`, `file2.cpp`, `file3.cpp`) in the `Jamroot` file for building an extension module or embedding application. Ensure whitespace separation between filenames. ```jam … file1.cpp file2.cpp file3.cpp … ``` -------------------------------- ### Get attribute from a const object using object key Source: https://www.boost.org/doc/libs/latest/libs/python/doc/html/reference/object_wrappers/boost_python_object_hpp Defines the `const_objattribute_policies` struct for accessing attributes of a const object when the key is provided as a Boost.Python `object`. The static `get` function retrieves the attribute value. ```cpp namespace boost { namespace python { namespace api { struct const_objattribute_policies { typedef object const& key_type; static object get(object const& target, object const& key); }; }}} static object get(object const& target, object const& key); ``` -------------------------------- ### Python Usage of Exposed C++ Function Source: https://www.boost.org/doc/libs/latest/libs/python/doc/html/article A Python script demonstrating the usage of the 'greet' function after it has been exposed via Boost.Python. It imports the 'hello' module and calls the 'greet' function within a loop, printing the results. ```python >>> import hello >>> for x in range(3): ... print hello.greet(x) ... hello Boost.Python world! ``` -------------------------------- ### Boost.Python Example: Custom to_python_converter Source: https://www.boost.org/doc/libs/latest/libs/python/doc/html/reference/function_invocation_and_creation/function_documentation This C++ example demonstrates how to register a custom converter for a C++ type `tag` to a Python type using `to_python_converter`. It includes conditional compilation for Python signature support. ```cpp #include #include #include "noddy.h" struct tag {}; tag make_tag() { return tag(); } using namespace boost::python; struct tag_to_noddy #if defined BOOST_PYTHON_SUPPORTS_PY_SIGNATURES //unnecessary overhead if py signatures are not supported : wrap_pytype<&noddy_NoddyType> //inherits get_pytype from wrap_pytype #endif { static PyObject* convert(tag const& x) { return PyObject_New(noddy_NoddyObject, &noddy_NoddyType); } }; BOOST_PYTHON_MODULE(to_python_converter) { def("make_tag", make_tag); to_python_converter(); //"true" because tag_to_noddy has member get_pytype } ``` -------------------------------- ### Use Exposed Python Class from Extension Module Source: https://www.boost.org/doc/libs/latest/libs/python/doc/html/article Demonstrates usage of the exposed World class from Python. Creates an instance, sets a message via set() method, and retrieves it using greet() method. ```Python >>> import hello >>> planet = hello.World() >>> planet.set('howdy') >>> planet.greet() 'howdy' ``` -------------------------------- ### Instantiate Binary Ufunc Source: https://www.boost.org/doc/libs/latest/libs/python/doc/html/numpy/tutorial/ufunc Creates an instance of the 'BinarySquare' Python class. This instance will be used to call the binary ufunc. ```cpp inst = ud(); ``` -------------------------------- ### Chaining Boost.Python Call Policies Source: https://www.boost.org/doc/libs/latest/libs/python/doc/html/tutorial/tutorial/functions Illustrates the syntax for composing multiple Boost.Python call policies by chaining them together. This allows for complex lifetime management scenarios by combining the behaviors of different policies. ```Python policy1 > > ``` -------------------------------- ### C++ Example: Exposing Functions and Classes with Signatures to Python Source: https://www.boost.org/doc/libs/latest/libs/python/doc/html/reference/function_invocation_and_creation/function_documentation Demonstrates using Boost.Python macros to expose C++ functions and class methods to Python, including custom docstrings and argument specifications. It shows how to handle function overloads and member functions, and how `BOOST_PYTHON_FUNCTION_OVERLOADS` and `BOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS` aid in generating comprehensive documentation. ```cpp #include #include #include #include #include #include #include using namespace boost::python; tuple f(int x = 1, double y = 4.25, char const* z = "wow") { return make_tuple(x, y, z); } BOOST_PYTHON_FUNCTION_OVERLOADS(f_overloads, f, 0, 3) struct X { tuple f(int x = 1, double y = 4.25, char const* z = "wow") { return make_tuple(x, y, z); } }; BOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS(X_f_overloads, X::f, 0, 3) tuple raw_func(tuple args, dict kw) { return make_tuple(args, kw); } BOOST_PYTHON_MODULE(args_ext) { def("f", f, (arg("x")=1, arg("y")=4.25, arg("z")="wow") , "This is f's docstring" ); def("raw", raw_function(raw_func)); def("f1", f, f_overloads("f1's docstring", args("x", "y", "z"))) class_("X", "This is X's docstring", init<>(args("self"))) .def("f", &X::f , "This is X.f's docstring" , args("self","x", "y", "z")) ; } ``` -------------------------------- ### Get attribute from a const object using string key Source: https://www.boost.org/doc/libs/latest/libs/python/doc/html/reference/object_wrappers/boost_python_object_hpp Defines the `const_attribute_policies` struct for accessing attributes of a const object using a C-style string as the key. It includes a static `get` function that returns a Boost.Python object representing the attribute's value. ```cpp namespace boost { namespace python { namespace api { struct const_attribute_policies { typedef char const* key_type; static object get(object const& target, char const* key); }; }}} static object get(object const& target, char const* key); ``` -------------------------------- ### Example: Extended slice of a Python list using Boost.Python Source: https://www.boost.org/doc/libs/latest/libs/python/doc/html/reference/object_wrappers/boost_python_slice_hpp Demonstrates how to perform an extended slice (e.g., selecting elements with a specific step) on a Python list using Boost.Python's slice functionality. This example specifically extracts odd-indexed elements. ```cpp using namespace boost::python; // Perform an extended slice of a Python list. // Warning: extended slicing was not supported for built-in types prior // to Python 2.3 list odd_elements(list l) { return l[slice(_,_,2)]; } ``` -------------------------------- ### Define pickle_suite with getinitargs in Boost.Python Source: https://www.boost.org/doc/libs/latest/libs/python/doc/html/reference/topics/pickle_support Implements a pickle_suite class that defines the getinitargs static method to return constructor arguments as a tuple. This is used when an object can be fully restored by passing arguments to the constructor without additional state restoration. ```cpp struct world_pickle_suite : boost::python::pickle_suite { static boost::python::tuple getinitargs(world const& w) { return boost::python::make_tuple(w.get_country()); } }; ``` -------------------------------- ### Simple Python Package Structure with Extension Modules Source: https://www.boost.org/doc/libs/latest/libs/python/doc/html/tutorial/tutorial/techniques Create a basic Python package directory structure where compiled extension modules (.pyd files) are placed directly in the package directory with an __init__.py file. This is the simplest approach but offers limited flexibility for adding pure Python code. ```text sounds/ __init__.py core.pyd filters.pyd io.pyd ``` -------------------------------- ### Boost.Python Example: Implicit Conversions in Python Source: https://www.boost.org/doc/libs/latest/libs/python/doc/html/reference/to_from_python_type_conversion/boost_python_implicit_hpp This Python example shows the effect of the C++ `implicitly_convertible` registrations. It demonstrates calling a C++ function that expects a custom `X` object with an integer, and passing an integer where an `X` object is expected, showcasing the automatic type conversions. ```python >>> from implicit_ext import * >>> x_value(X(42)) 42 >>> x_value(42) 42 >>> x = make_x(X(42)) >>> x_value(x) 42 ``` -------------------------------- ### Boost.Python Call Policies Example Source: https://www.boost.org/doc/libs/latest/libs/python/doc/html/tutorial/tutorial/functions Demonstrates the use of Boost.Python call policies like `return_internal_reference` and `with_custodian_and_ward` to manage object lifetimes and references when exposing C++ functions to Python. It explains how policy arguments specify which function arguments are involved. ```Python def("f", f, return_internal_reference<1, with_custodian_and_ward<1, 2> >()); ``` -------------------------------- ### C++ Module Definition with Boost.Python Enum Example Source: https://www.boost.org/doc/libs/latest/libs/python/doc/html/reference/high_level_components/boost_python_enum_hpp An example demonstrating how to expose a C++ enumeration type (`color`) to Python using Boost.Python. It defines the enumeration, a C++ function that uses it, and then uses `enum_` to create a Python representation of the enumeration and a module function. ```cpp #include #include #include using namespace boost::python; enum color { red = 1, green = 2, blue = 4 }; color identity_(color x) { return x; } BOOST_PYTHON_MODULE(enums) { enum_("color") .value("red", red) .value("green", green) .export_values() .value("blue", blue) ; def("identity", identity_); } ``` -------------------------------- ### Example: Summation over a slice of std::vector using Boost.Python Source: https://www.boost.org/doc/libs/latest/libs/python/doc/html/reference/object_wrappers/boost_python_slice_hpp Shows how to calculate a partial sum over a `std::vector` using Boost.Python's slice and `get_indices`. This example safely handles potential exceptions from `get_indices` and iterates through the determined range to compute the sum. ```cpp double partial_sum(std::vector const& Foo, const slice index) { slice::range::const_iterator> bounds; try { bounds = index.get_indices<>(Foo.begin(), Foo.end()); } catch (std::invalid_argument) { return 0.0; } double sum = 0.0; while (bounds.start != bounds.stop) { sum += *bounds.start; std::advance( bounds.start, bounds.step); } sum += *bounds.start; return sum; } ``` -------------------------------- ### Exposing C++ Function using Boost.Python Source: https://www.boost.org/doc/libs/latest/libs/python/doc/html/article This snippet demonstrates the concise way to expose the C++ 'greet' function to Python using Boost.Python. It utilizes the BOOST_PYTHON_MODULE macro and the def function for simple and automatic argument/result conversion and exception handling. ```cpp #include using namespace boost::python; BOOST_PYTHON_MODULE(hello) { def("greet", greet, "return one of 3 parts of a greeting"); } ``` -------------------------------- ### Boost.Python long_ Example: Factorial Calculation (C++) Source: https://www.boost.org/doc/libs/latest/libs/python/doc/html/reference/object_wrappers/boost_python_long_hpp An example demonstrating the use of `boost::python::long_` in C++ to compute a factorial function. This ensures that the calculation can handle arbitrarily large numbers without overflowing, leveraging Python's arbitrary-precision integers. ```cpp namespace python = boost::python; // compute a factorial without overflowing python::long_ fact(long n) { if (n == 0) return python::long_(1); else return n * fact(n - 1); } ``` -------------------------------- ### Implement and expose UnarySquare functor with unary_ufunc Source: https://www.boost.org/doc/libs/latest/libs/python/doc/html/numpy/reference/unary_ufunc Complete example demonstrating how to define a C++ unary functor (UnarySquare) with required typedefs, expose it as a Python class using Boost.Python, and use unary_ufunc to create a callable __call__ method. The example creates an instance and invokes it with a scalar value. ```C++ namespace p = boost::python; namespace np = boost::python::numpy; struct UnarySquare { typedef double argument_type; typedef double result_type; double operator()(double r) const { return r * r;} }; p::object ud = p::class_ >("UnarySquare").def("__call__", np::unary_ufunc::make()); p::object inst = ud(); std::cout << "Square of unary scalar 1.0 is " << p::extract (p::str(inst.attr("__call__")(1.0))) << std::endl ; ```