How can I call C++ module functions from C++ but select the function from python? See example below
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.
I would also like it to be very efficient, hopefully by basically unwrapping the boost::python::object and extracting the boost::function<> out of it.
Here is the python file
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
C++ module code (compiles, but does not run.. you can see my intent):
#include <sys/time.h>
#include <stdlib.h>
#include <boost/function.hpp>
#include <boost/python.hpp>
struct TestClass
{
TestClass() { }
int a() const { return rand()%4; }
int b() const { return rand()%64; }
template<typename T>
void BenchMark(T & aUnknownFunction)
{
timeval begin, end;
long long sum(0);
gettimeofday(&begin, NULL);
__asm__ __volatile__ ("cpuid");
for (int x(0); x!=100000; ++x)
sum += aUnknownFunction();
__asm__ __volatile__ ("cpuid");
gettimeofday(&end, NULL);
std::cout << "Time: " << 1000000 * (end.tv_sec - begin.tv_sec) + (end.tv_usec - begin.tv_usec) << std::endl;
srand(sum);
}
void CallSomeClassMemberFunction(boost::python::object &aTest)
{
boost::function<int ()> unknownFunction = boost::python::extract<boost::function<int ()> >(aTest) ; // i don't think this works as I want
BenchMark( unknownFunction );
}
void Reference()
{
boost::function<int ()> unknownFunction = boost::bind(&TestClass::a, this);
BenchMark( unknownFunction );
}
};
BOOST_PYTHON_MODULE(stackoverflow)
{
boost::python::class_<TestClass>("TestClass")
.def("a",&TestClass::a)
.def("b",&TestClass::b)
.def("CallSomeClassMemberFunction",&TestClass::CallSomeClassMemberFunction)
.def("Reference",&TestClass::Reference)
;
}
If you can get it to run, would love to see your timings as well.