Referencing a C++ allocated object in pybind11
<p>I'm trying to create a python binding with pybind11 that references a C++ instance whose memory is handled on the C++ side. Here is some example code:</p>

<pre><code>import &lt;pybind11/pybind11&gt;

struct Dog {
    void bark() { printf("Bark!\n"); }
};

int main()
{
  auto dog = new Dog;
  Py_Initialize();
  initexample(); // Initialize the example python module for import 

  // TBD - Add binding  between dog and example.dog .

  PyRun_StringFlags("import example\n"
                    "\n"
                    "example.dog.bark()\n"  // Access the C++ allocated object dog.
                    , Py_file_input, main_dict, main_dict, NULL);
  Py_Finalize();
}
</code></pre>

<p>I'm stuck on how to create the link between the python <code>example.dog</code> and the C++ <code>dog</code> variable. </p>

<p>I can't use <code>py:class_&lt;Dog&gt;.def(py::init&lt;&gt;())</code> as that will allocate a new instance of <code>Dog</code>, which is not what I want. </p>

<p>I found an answer to my own question. The trick was a combination of the following two concepts:</p>

<ul>
<li>Create an independent function that returns the singleton.</li>
<li>Create binding to the singleton class <strong>without</strong> binding a constructor. </li>
</ul>

<p>The following example illustrates the technique:</p>

<pre><code>#include &lt;Python.h&gt;
#include &lt;pybind11/pybind11.h&gt;

namespace py = pybind11;
using namespace pybind11::literals;

// Singleton to wrap
struct Singleton
{
  Singleton() : x(0) {}

  int exchange(int n)  // set x and return the old value
  {
    std::swap(n, x);
    return n;
  }

  // Singleton reference 
  static Singleton&amp; instance()
  {
    static Singleton just_one;
    return just_one;
  }

  int x;
};

PYBIND11_PLUGIN(example) {
    py::module m("example", "pybind11 example plugin");

    // Use this function to get access to the singleton
    m.def("get_instance",
          &amp;Singleton::instance,
          py::return_value_policy::reference,
          "Get reference to the singleton");

    // Declare the singleton methods
    py::class_&lt;Singleton&gt;(m, "Singleton")
      // No init!
      .def("exchange",
           &amp;Singleton::exchange,
           "n"_a,
           "Exchange and return the current value"
           )
      ;

    return m.ptr();
}

int main(int argc, char **argv)
{
  Py_Initialize();

  PyObject* main_module = PyImport_AddModule("__main__");
  PyObject* main_dict = PyModule_GetDict(main_module);

  initexample();

  // Call singleton from c++
  Singleton::instance().exchange(999);

  // Populate the example class with two static pointers to our instance.
  if (PyRun_StringFlags("import example\n"
                        "\n"
                        "example.s1 = example.get_instance()\n"
                        "example.s2 = example.get_instance()\n",
                        Py_file_input, main_dict, main_dict, NULL) == nullptr)
      PyErr_Print();

  // Test referencing the singleton references
  if (PyRun_StringFlags("from example import *\n"
                        "\n"
                        "for i in range(3):\n"
                        "  print s1.exchange(i*2+1)\n"
                        "  print s2.exchange(i*2+2)\n"
                        "print dir(s1)\n"
                        "print help(s1.exchange)\n"
                        ,
                        Py_file_input, main_dict, main_dict, NULL) == nullptr)
      PyErr_Print();

  Py_Finalize();

  exit(0);
}
</code></pre>

python c++ pybind11