1

我正在尝试使用 boost.python 向 Python 公开一组 C++ 类。这些类结合了纯虚方法和共享指针,通过多态实现了一致的接口,并进行了一些简单的内存管理(刚好够用)。这是完整的来源:

// Boost stuff.
#include <boost/shared_ptr.hpp>
#include <boost/python.hpp>

class RoutingInterface
{
public:

    virtual ~RoutingInterface()
    {
        // Do nothing.
    }

    virtual const char* begin(unsigned int& size, unsigned int limit) = 0;
    virtual const char* advance(const char* data, unsigned int& size, unsigned int limit) = 0;
    virtual void finish(const char* data) = 0;
};

class Route
{
public:

    virtual ~Route()
    {
        // Do nothing.
    }

    virtual RoutingInterface* get_interface() = 0;
    virtual void release_instance(RoutingInterface* instance) = 0;
};

class Router
{
public:

    // Useful types.
    typedef boost::shared_ptr<Route> route_ptr;

private:

    std::map<std::string, route_ptr> Routes;

public:

    // Working with routes.
    void add_route(std::string path, route_ptr route)
    {
        Routes[path] = route;
    }

    void remove_route(std::string path)
    {
        auto found = Routes.find(path);
        if(found != Routes.end())
        {
            // Found a nothing.
            Routes.erase(path);
        }           
    }

    route_ptr route_path(std::string path)
    {
        auto found = Routes.find(path);
        if(found != Routes.end())
        {
            // Found a nothing.
            return found->second;
        }

        // Found a nothing.
        return Router::route_ptr();
    }
};

BOOST_PYTHON_MODULE(http_server)
{
    class_<RoutingInterface, boost::noncopyable>("RoutingInterface", no_init)
        .def("get_interface", pure_virtual(&RoutingInterface::begin))
        .def("release_instance", pure_virtual(&RoutingInterface::advance))
        .def("release_instance", pure_virtual(&RoutingInterface::finish));

    class_<Route, boost::noncopyable>("Route", no_init)
        .def("get_interface", pure_virtual(&Route::get_interface),
            return_value_policy<reference_existing_object>())
        .def("release_instance", pure_virtual(&Route::release_instance));

    class_<Router, router_ptr>("Router", init<log_ptr>())
        .def("add_route", &Router::add_route)
        .def("remove_route", &Router::remove_route)
        .def("route_path", &Router::route_path,
            return_value_policy<reference_existing_object>());
}

我将实现从 Route 和 RoutingInterface 类继承的类,并由工厂方法构造,然后从 Python 调用。Router 类是一个容器,用于存储路由并允许从中进行搜索。

这就是问题所在:我无法将描述的 3 个类公开给 Python,并想出一些可以实际编译的东西。我尝试了各种排列,最近一次尝试在上面的源代码中显示(不编译)。有任何想法吗?

4

0 回答 0