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 mymodule #this is a C++ module I wrote t = mymodule .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 ----------------------- 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(mymodule) { boost::python::class_<TestClass>("TestClass") .def("a",&TestClass::a) .def("b",&TestClass::b) .def("CallSomeClassMemberFunction",&TestClass::CallSomeClassMemberFunction) .def("Reference",&TestClass::Reference) ; } ---- The idea is to do this efficiently. I have been able to successfully repeatedly evaluate the boost::python::object, but since I am doing it a lot, i'd like to avoid paying the overhead every time. I also posted this on stackoverflow, if you are interested in replying there: http://stackoverflow.com/questions/13961486/unwrapping-a-boostfunction-from-boostpythonobject-with-extract Thanks in advance _______________________________________________ Cplusplus-sig mailing list Cplusplus-sig@python.org http://mail.python.org/mailman/listinfo/cplusplus-sig