使用extract从boost :: python :: object中展开boost :: function

时间:2012-12-19 21:27:59

标签: c++ boost boost-python boost-function

如何从C ++调用C ++模块函数,但从python中选择函数?见下面的例子

我知道我可以手动设置字符串映射,并选择我想要运行的函数,但我想要一个更清晰的python解决方案。

我希望它非常有效,希望通过基本解开boost :: python :: object并解压缩boost :: function<>出来的。

这是python文件

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 ++模块代码(编译,但不运行..你可以看到我的意图):

#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)
        ;
}

如果你可以让它运行,也很乐意看到你的时间。

0 个答案:

没有答案