Sending Python function as Boost.Function argument
<p>Things are getting complicated in my world of trying to mesh Python code with my C++.</p>

<p>Essentially, I want to be able to assign a callback function to be used after an HTTP call receives a response, and I want to be able to do this from either C++ or Python.</p>

<p>In other words, I want to be able to call this from C++:</p>

<pre><code>http.get_asyc("www.google.ca", [&amp;](int a) { std::cout &lt;&lt; "response recieved: " &lt;&lt; a &lt;&lt; std::endl; });
</code></pre>

<p>and this from Python:</p>

<pre><code>def f(r):
    print str.format('response recieved: {}', r)

http.get_async('www.google.ca', f)
</code></pre>

<p>I have set up a <a href="http://coliru.stacked-crooked.com/a/54a347cdce64c3f1" rel="nofollow noreferrer">demo on Coliru</a> that shows exactly what I'm trying to accomplish. Here is the code and the error that I am getting:</p>

<h1>C++</h1>

<pre><code>#include &lt;boost/python.hpp&gt;
#include &lt;boost/function.hpp&gt;

struct http_manager
{
    void get_async(std::string url, boost::function&lt;void(int)&gt; on_response)
    {
        if (on_response)
        {
            on_response(42);
        }
    }
} http;

BOOST_PYTHON_MODULE(example)
{
    boost::python::class_&lt;http_manager&gt;("HttpManager", boost::python::no_init)
        .def("get_async", &amp;http_manager::get_async);

    boost::python::scope().attr("http") = boost::ref(http);
}
</code></pre>

<h1>Python</h1>

<pre><code>import example
def f(r):
    print r
example.http.get_async('www.google.ca', f)
</code></pre>

<h1>Error</h1>

<pre><code>Traceback (most recent call last):
  File "&lt;stdin&gt;", line 4, in &lt;module&gt;
Boost.Python.ArgumentError: Python argument types in
    HttpManager.get_async(HttpManager, str, function)
did not match C++ signature:
    get_async(http_manager {lvalue}, std::__cxx11::basic_string&lt;char, std::char_traits&lt;char&gt;, std::allocator&lt;char&gt; &gt;, boost::function&lt;void (int)&gt;)
</code></pre>

<p>I'm not sure why the <code>function</code> is not being converted to a <code>boost::function</code> automatically.</p>

<p>I have asked a <a href="https://stackoverflow.com/questions/30553586/boost-python-and-boost-function">vaguely similar question</a> on SO before and got an amazing answer. I also wonder if a similar method in the answer given there could be applied to this use-case as well.</p>

<p>Thank you very much for any and all support!</p>