Note that there are some explanatory texts on larger screens.

plurals
  1. POUnwrapping a boost::function from boost::python::object with extract
    primarykey
    data
    text
    <p>How can I call C++ module functions from C++ but select the function from python? See example below</p> <p>I know I can setup a map of strings manually, and select the function I want to run, but I'd like a cleaner python solution. </p> <p>I would also like it to be very efficient, hopefully by basically unwrapping the boost::python::object and extracting the boost::function&lt;> out of it.</p> <p>Here is the python file</p> <pre><code>import stackoverflow #this is a C++ module I wrote t = stackoverflow.TestClass() t.Reference() # time invoking a boost::function 100k times t.CallSomeClassMemberFunction(t.a) # instead of choosing a function directly, i want to pass in which function I want to invoke from python </code></pre> <p>C++ module code (compiles, but does not run.. you can see my intent):</p> <pre><code>#include &lt;sys/time.h&gt; #include &lt;stdlib.h&gt; #include &lt;boost/function.hpp&gt; #include &lt;boost/python.hpp&gt; struct TestClass { TestClass() { } int a() const { return rand()%4; } int b() const { return rand()%64; } template&lt;typename T&gt; void BenchMark(T &amp; aUnknownFunction) { timeval begin, end; long long sum(0); gettimeofday(&amp;begin, NULL); __asm__ __volatile__ ("cpuid"); for (int x(0); x!=100000; ++x) sum += aUnknownFunction(); __asm__ __volatile__ ("cpuid"); gettimeofday(&amp;end, NULL); std::cout &lt;&lt; "Time: " &lt;&lt; 1000000 * (end.tv_sec - begin.tv_sec) + (end.tv_usec - begin.tv_usec) &lt;&lt; std::endl; srand(sum); } void CallSomeClassMemberFunction(boost::python::object &amp;aTest) { boost::function&lt;int ()&gt; unknownFunction = boost::python::extract&lt;boost::function&lt;int ()&gt; &gt;(aTest) ; // i don't think this works as I want BenchMark( unknownFunction ); } void Reference() { boost::function&lt;int ()&gt; unknownFunction = boost::bind(&amp;TestClass::a, this); BenchMark( unknownFunction ); } }; BOOST_PYTHON_MODULE(stackoverflow) { boost::python::class_&lt;TestClass&gt;("TestClass") .def("a",&amp;TestClass::a) .def("b",&amp;TestClass::b) .def("CallSomeClassMemberFunction",&amp;TestClass::CallSomeClassMemberFunction) .def("Reference",&amp;TestClass::Reference) ; } </code></pre> <p>If you can get it to run, would love to see your timings as well.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload