2

如何从 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)
        ;
}

如果你能让它运行,也很想看看你的时间安排。

4

0 回答 0