title: Cython: How to wrap a C++ function that returns a C++ object?
body: <p>I'm working on a Python project where I'd like to interface with a C++ package that has already been written.  Since I'll be using Cython in other portions of this project, I'd prefer to wrap using Cython.</p>
  
  <p>In brief, I need to wrap a function, FooBar, that returns an object of custom class type Bar.</p>
  
  <p>Here's the Bar.h:</p>
  
  <pre><code>#include &lt;cstddef&gt; // For size_t
  #include &lt;vector&gt;
  
  /* data returned by function FooBar()*/
  class Bar {
  public:
      size_t X;
      std::vector&lt;size_t&gt; Y;      
      std::vector&lt;double&gt; Z;  
      std::vector&lt;double&gt; M;  
      std::vector&lt;size_t&gt; N;  
  
  };
  
  
  Bar FooBar(const std::vector&lt;double&gt; &amp; O, size_t P, size_t Q);
  </code></pre>
  
  <p>And PyBar.pyx:</p>
  
  <pre><code>from libcpp.vector cimport vector
  
  cdef extern from "Bar.h":
      cdef cppclass Bar:
          size_t X
          vector[size_t] Y    
          vector[double] Z    
          vector[double] M 
          vector[size_t] N    
      cdef Bar FooBar(const vector[double] &amp; O, size_t P, size_t Q)
  
  cdef class PyBar:
      cdef Bar *thisptr      # hold a C++ instance which we're wrapping
  
      def __cinit__(self, O, P, Q):
          C_Bar = FooBar(O, P, Q)
          self.thisptr = &amp;C_Bar
  
      def __dealloc__(self):
          del self.thisptr
  </code></pre>
  
  <p><strong>Actual Question:</strong> Is this even the right approach to what I want to do?  For reference, if I just tried to wrap the class by itself I have had no problem: I can import the module, create objects using PyBar(), and underlying C methods implemented on the class would work.   The issue is trying to wrap a function that returns objects of the C++ class.  In the wild, I'll never actually want to create PyBar representation of any Bar object that wasn't created by FooBar, so this is the approach I decided upon after much head scratching. </p>