Boost Python

Composed from the comp.python.c newsgroup hosted on news.gmane.org. Seeofficial boost.python FAQ. The constructor AND the destructor of a C class that I am trying to wrap are private (this class is designed following the singleton DP). Thanks for the helpful tips on your website. I tried to follow these steps using MSVS 2019, boost 1.70, Python 3.7. When I convert the dll to pyd and try to import it in the interpreter it returns 'ImportError: DLL load failed: The specified module could not be found.' The boost::python::object provides a generalized interface to Python objects. To construct one from a PyObject., one must first construct a boost::python::handle, which is essentially a smart pointer designed to manage reference-counted Python objects (PyObject. or derived types).

Boost/python.hpp: no such file or directory

Pointers and smart pointers

Pybind11 Vs Boost Python

Since Python handles memory allocation and garbage collection automatically, the concept of a 'pointer' is not meaningful in Python. However, many C++ APIs expose either raw pointers or shared pointers, to wrap these APIs we need to deal with pointers.

Raw C++ Pointers

The lifetime of C++ objects created by new A can be handled by Python's garbage collection by using the manage_new_object return policy:

Boost Python Extract

A sample python program:

Smart pointers

Boost Python Install

The usage of smart pointers (e.g. boost::shared_ptr<T>) is another common way to give away ownership of objects in C++. These kinds of smart pointer are automatically handled if you declare their existence when declaring the class to boost::python. This is done by including the holding type as a template parameter to class_<>, like in the following example:

Lego Boost Python

A sample python program:

Smart Pointer Example with OpenSceneGraph

The Node.cpp file:

This creates an opaque Node pointer. It can be extended to expose members of Node objects, or used as is to return opaque references to Node objects. For opaque references, the module must still be imported by the Python app. If Node.pyd is in a package directory, importing it in the __init__.py file in that directory seems to be a simple, workable solution.