将Python函数作为增强功能阿古门

2024-09-30 10:40:38 发布

您现在位置:Python中文网/ 问答频道 /正文

在我的世界里,试图用我的C++来计算Python代码变得越来越复杂。在

本质上,我希望能够在HTTP调用接收到响应后分配一个回调函数,并且我希望能够从C++或Python中执行。在

换句话说,我希望能够从C++调用这个:

http.get_asyc("www.google.ca", [&](int a) { std::cout << "response recieved: " << a << std::endl; });

这是来自Python的:

^{pr2}$

我已经设置了一个demo on Coliru,它精确地显示了我要完成的任务。下面是我得到的代码和错误:

C++ +/H1>
#include <boost/python.hpp>
#include <boost/function.hpp>

struct http_manager
{
    void get_async(std::string url, boost::function<void(int)> on_response)
    {
        if (on_response)
        {
            on_response(42);
        }
    }
} http;

BOOST_PYTHON_MODULE(example)
{
    boost::python::class_<http_manager>("HttpManager", boost::python::no_init)
        .def("get_async", &http_manager::get_async);

    boost::python::scope().attr("http") = boost::ref(http);
}

Python

import example
def f(r):
    print r
example.http.get_async('www.google.ca', f)

错误

Traceback (most recent call last):
  File "<stdin>", line 4, in <module>
Boost.Python.ArgumentError: Python argument types in
    HttpManager.get_async(HttpManager, str, function)
did not match C++ signature:
    get_async(http_manager {lvalue}, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, boost::function<void (int)>)

我不知道为什么function没有自动转换为boost::function。在

我以前问过a vaguely similar question,得到了一个惊人的答案。我还想知道答案中类似的方法是否也适用于这个用例。在

非常感谢您的支持!在


Tags: 代码httpgetasynconexampleresponsemanager
2条回答

当一个函数通过Boost.Python被调用,Boost.Python将查询注册表,根据所需的C++类型,为每个调用方的参数找到一个合适的Python转换器。如果找到一个转换器,它知道如何将Python对象转换为C++对象,那么它将使用转换器构造C++对象。如果没有找到合适的转换器,则Boost.Python将引发ArgumentError异常。在

已注册from Python转换器:

  • 对于支持的类型自动Boost.Python,例如int和{}
  • 隐式地用于^{}公开的类型。默认情况下,生成的Python类将持有一个嵌入的实例,该实例是^ {< CD5> } C++对象,并使用嵌入实例登记到Python和Python转换器,用于Python类和类型^ {< CD5> }。在
  • 显式地通过boost::python::converter::registry::push_back()

测试可兑换性和构造对象的步骤分为两个不同的步骤。由于没有从Python converter为boost::function<void(int)>注册,Boost.Python将引发ArgumentError异常。Boost.Python不会尝试构造boost::function<void(int)>对象,尽管boost::function<void(int)>可以从boost::python::object构造。在


要解决此问题,请考虑使用一个shim函数来延迟boost::function<void(int)>的构造,直到boost::python::object通过Boost.Python图层:

void http_manager_get_async_aux(
  http_manager& self, std::string url, boost::python::object on_response)
{
  return self.get_async(url, on_response);
}

...

BOOST_PYTHON_MODULE(example)
{
  namespace python = boost::python;
  python::class_<http_manager>("HttpManager", python::no_init)
    .def("get_async", &http_manager_get_async_aux);

  ...
}

这是一个完整的例子demonstrating这种方法:

^{pr2}$

交互式使用:

>>> import example
>>> result = 0
>>> def f(r):
...     global result
...     result = r
...
>>> assert(result == 0)
>>> example.http.get_async('www.google.com', f)
>>> assert(result == 42)
>>> try:
...     example.http.get_async('www.google.com', 42)
...     assert(False)
... except TypeError:
...    pass
...

另一种方法是显式地为boost::function<void(int)>注册from Python转换器。这样做的好处是所有函数都通过Boost.Python可以使用转换器(例如,不需要为每个功能编写垫片)。但是,需要为每个C++类型注册一个转换。下面是一个示例demonstrating显式注册boost::function<void(int)>boost::function<void(std::string)>的自定义转换器:

#include <boost/python.hpp>
#include <boost/function.hpp>

struct http_manager
{
  void get_async(std::string url, boost::function<void(int)> on_response)
  {
    if (on_response)
    {
      on_response(42);
    }
  }
} http;

/// @brief Type that allows for registration of conversions from
///        python iterable types.
struct function_converter
{
  /// @note Registers converter from a python callable type to the
  ///       provided type.
  template <typename FunctionSig>
  function_converter&
  from_python()
  {
    boost::python::converter::registry::push_back(
      &function_converter::convertible,
      &function_converter::construct<FunctionSig>,
      boost::python::type_id<boost::function<FunctionSig>>());

    // Support chaining.
    return *this;
  }

  /// @brief Check if PyObject is callable.
  static void* convertible(PyObject* object)
  {
    return PyCallable_Check(object) ? object : NULL;
  }

  /// @brief Convert callable PyObject to a C++ boost::function.
  template <typename FunctionSig>
  static void construct(
    PyObject* object,
    boost::python::converter::rvalue_from_python_stage1_data* data)
  {
    namespace python = boost::python;
    // Object is a borrowed reference, so create a handle indicting it is
    // borrowed for proper reference counting.
    python::handle<> handle(python::borrowed(object));

    // Obtain a handle to the memory block that the converter has allocated
    // for the C++ type.
    typedef boost::function<FunctionSig> functor_type;
    typedef python::converter::rvalue_from_python_storage<functor_type>
                                                                storage_type;
    void* storage = reinterpret_cast<storage_type*>(data)->storage.bytes;

    // Allocate the C++ type into the converter's memory block, and assign
    // its handle to the converter's convertible variable.
    new (storage) functor_type(python::object(handle));
    data->convertible = storage;
  }
};

BOOST_PYTHON_MODULE(example)
{
  namespace python = boost::python;
  python::class_<http_manager>("HttpManager", python::no_init)
    .def("get_async", &http_manager::get_async);

  python::scope().attr("http") = boost::ref(http);

  // Enable conversions for boost::function.
  function_converter()
    .from_python<void(int)>()
    // Chaining is supported, so the following would enable
    // another conversion.
    .from_python<void(std::string)>()
    ;
}

一种解决方案是添加重载函数:

void get_async(std::string url, boost::python::object obj)
{
    if (PyCallable_Check(obj.ptr()))
        get_async(url, static_cast<boost::function<void(int)>>(obj));
}

然后暴露这个特定的过载:

^{pr2}$

或者,如果你不想用python的东西污染你的主类,那么你可以创建一个包装类。事情看起来也干净多了:

struct http_manager_wrapper : http_manager
{
    void get_async(std::string url, boost::python::object obj)
    {
        if (PyCallable_Check(obj.ptr()))
            http_manager::get_async(url, obj);
    }

} http_wrapper;

BOOST_PYTHON_MODULE(example)
{
    boost::python::class_<http_manager_wrapper>("HttpManager", boost::python::no_init)
        .def("get_async", &http_manager_wrapper::get_async);

    boost::python::scope().attr("http") = boost::ref(http_wrapper);
}

更新:另一个选择是使用python可调用的boost函数转换器。这将解决单例问题,并且不需要更改主类。在

struct http_manager
{
    void get_async(std::string url, boost::function<void(int)> on_response)
    {
        if (on_response)
        {
            on_response(42);
        }
    }
} http;

struct BoostFunc_from_Python_Callable
{
    BoostFunc_from_Python_Callable()
    {
        boost::python::converter::registry::push_back(&convertible, &construct, boost::python::type_id< boost::function< void(int) > >());
    }

    static void* convertible(PyObject* obj_ptr)
    {
        if (!PyCallable_Check(obj_ptr)) 
            return 0;
        return obj_ptr;
    }

    static void construct(PyObject* obj_ptr, boost::python::converter::rvalue_from_python_stage1_data* data)
    {
        boost::python::object callable(boost::python::handle<>(boost::python::borrowed(obj_ptr)));
        void* storage = ((boost::python::converter::rvalue_from_python_storage< boost::function< void(int) > >*) data)->storage.bytes;
        new (storage)boost::function< void(int) >(callable);
        data->convertible = storage;
    }
};

BOOST_PYTHON_MODULE(example)
{
    // Register function converter
    BoostFunc_from_Python_Callable();

    boost::python::class_<http_manager>("HttpManager", boost::python::no_init)
        .def("get_async", &http_manager::get_async);

    boost::python::scope().attr("http") = boost::ref(http);
}

相关问题 更多 >

    热门问题