title: Get access to C++ class created in python from C++
body: <p>How to do this</p>
  
  <pre><code>c++ -&gt; Python -&gt; c++
   ^               |
   |               |
   -----------------
  </code></pre>
  
  <ol>
  <li>C++ app is hosting python.</li>
  <li>Python creates a class, which is actually a wrapping to c/c++ object</li>
  <li>How to get access from hosting c++ to c/c++ pointer of this object created by python? </li>
  </ol>
  
  <p><strong>Example with code:</strong></p>
  
  <p>Imagine I have a C++ class wrapped for python (e.g. using boost.python)</p>
  
  <pre><code>// foo.cpp
  #include &lt;boost/python.hpp&gt;
  
  struct Cat {
     Cat (int fur=4): _fur{i} { }
     int get_fur() const { return _fur; }
  private:
     int _fur;
  };
  
  BOOST_PYTHON_MODULE(foo) {
  using namespace boost::python;
  
  class_&lt;Cat&gt;("Cat", init&lt;int&gt;())
     .def("get_fur", &amp;A::get_fur, "Density of cat's fur");
  </code></pre>
  
  <p>}</p>
  
  <p>Now <strong>I'm hosting a python in C++</strong>. A python script creates <strong>Cat</strong> => A c++  Cat instance is created underneath. How to get a pointer to c++ instance of Cat from hosting c++ (from C++ to C++)?</p>
  
  <pre><code>#include &lt;Python.h&gt;
  
  int
  main(int argc, char *argv[])
  {
    Py_SetProgramName(argv[0]);  /* optional but recommended */
    Py_Initialize();
    PyRun_SimpleString("from cat import Cat \n"
                       "cat = Cat(10) \n");
  
    // WHAT to do here to get pointer to C++ instance of Cat
     ... ??? ...
  
    std::cout &lt;&lt; "Cat's fur: " &lt;&lt; cat-&gt;get_fur() &lt;&lt; std::endl
  
    Py_Finalize();
    return 0;
  }
  </code></pre>
  
  <p><strong>Real application</strong>
  The real problem is this: we have a c++ framework which has pretty complex initialization and configuration phase where performance is not critical; and then processing phase, where performance is everything. There is a python wrapping for the framework. Defining things in python is very convenient but running from python is still slower than pure c++ code. It is tempting for many reasons to do this configuration/initialization phase in python, get pointers to underneath C++ objects and then run in "pure c++ mode". It would be easy if we could write everything from scratch, but we have already pretty much defined (30 years old) c++ framework. </p>