使用Boost::Python包装带参数的纯虚方法

2 投票
1 回答
1775 浏览
提问于 2025-04-15 19:22

我现在正在尝试通过Boost::Python把一个C++接口(纯虚类)暴露给Python。这个C++接口是:

Agent.hpp

#include "Tab.hpp"
class Agent
{
    virtual void start(const Tab& t) = 0;
    virtual void stop() = 0;
};

通过阅读“官方”的教程,我成功写出了下一个Python包装器并进行了构建:

Agent.cpp

#include <boost/python.hpp>
#include <Tabl.hpp>
#include <Agent.hpp>
using namespace boost::python;

struct AgentWrapper: Agent, wrapper<Agent>
{
    public:
    void start(const Tab& t)
    {
        this->get_override("start")();
    }
    void stop()
    {
        this->get_override("stop")();
    }
};

BOOST_PYTHON_MODULE(PythonWrapper)
{
    class_<AgentWrapper, boost::noncopyable>("Agent")
        .def("start", pure_virtual(&Agent::start) )
        .def("stop", pure_virtual(&Agent::stop) )
    ;
}

需要注意的是,我在构建时没有遇到任何问题。不过,我担心的是,正如你所看到的,AgentWrapper::start似乎没有把任何参数传递给Agent::start,具体在:

void start(const Tab& t)
{
    this->get_override("start")();
}

那么,Python包装器怎么知道“start”需要一个参数呢?我该怎么做呢?

1 个回答

4

get_override函数会返回一个叫做< a href="http://www.cs.brown.edu/~jwicks/boost/libs/python/doc/v2/wrapper.html#override-spec" rel="nofollow noreferrer">override的对象,这个对象有很多不同的版本,可以处理不同数量的参数。所以你可以直接这样做:

void start(const Tab& t)
{
    this->get_override("start")(t);
}

你试过这样做吗?

撰写回答