title: How to write a wrapper over functions and member functions that executes some code before and after the wrapped function?
body: <p>I'm trying to write some wrapper class or function that allows me to execute some code before and after the wrapped function.</p>
  
  <pre><code>float foo(int x, float y)
  {
      return x * y;
  }
  
  BOOST_PYTHON_MODULE(test)
  {
       boost::python::def("foo", &lt;somehow wrap "&amp;foo"&gt;);
  }
  </code></pre>
  
  <p>Ideally, the wrapper should be generic, working for functions and member functions alike, with any signature.</p>
  
  <p>More info:</p>
  
  <p>I'm looking for a simple way to release/re-acquire the GIL around my expensive C++ calls without having to manually write thin wrappers like this:</p>
  
  <pre><code>float foo_wrapper(int x, float y)
  {
      Py_BEGIN_ALLOW_THREADS
      int result = foo(x, y);
      Py_END_ALLOW_THREADS
      return result;
  }
  
  BOOST_PYTHON_MODULE(test)
  {
       boost::python::def("foo", &amp;foo_wrapper);
  }
  </code></pre>
  
  <p>This kind of wrapper will be repeated several times for all kinds of functions, and I would like to find a solution that would allow me to avoid coding all of them.</p>
  
  <p>I have tried some approaches, but the best I could come with required the user to explicitly state the types of return values and parameters, like:</p>
  
  <pre><code>boost::python::def("foo", &amp;wrap_gil&lt;float, int, float&gt;(&amp;foo_wrapper));
  </code></pre>
  
  <p>But it seems to me it should be possible to just pass the pointer to the function (&amp;foo_wrapper) and let the compiler figure out the types. </p>
  
  <p>Does anyone know a technique I could use or point me in the right direction?</p>
  
  <p>Cheers!</p>