pybind回调功能生成

发布于 2025-02-13 04:37:21 字数 1067 浏览 2 评论 0原文

我正在为C ++函数编写Python绑定代码:

void cls::acceptCall(My::namespace::Reply reply)
{
    std::cout <<__FUNCTION__ << std::endl;
    reply(My::namespace::Result::Ok, nullptr);
}
using Reply = std::function<void(Result result, std::exception_ptr error)>;
enum class Result {Ok,NOT_OK }

绑定代码:

py::class_<APIExtProvider>(m, "APIExtProvider")
    .def("acceptCall", &APIExtProvider::acceptCall, py::call_guard<py::gil_scoped_release>())

Python_call:

result = pyunifiedphone.Result.OK
exception = pyunifiedphone.Exception()

def reply_method(result, exception):
    return None
     
 provider.acceptCall(reply_method)

但是,我得到此错误:

typeError:acceptCall():不兼容的函数参数。支持以下参数类型: 1。(self:pyunifiedphone.apiextprovider,arg1:callable [[pyunifiedphone.result,pyunifiedphone.exception],none])) - &gt;没有

调用:&lt; pyunifiedphone.apiextprovider对象,请访问0x7f2b6aa149b0&gt; ,,&lt; function reply_method at 0x7f2b6abfa1f0&gt; gt; gt;

正确的绑定方式是什么?

I am writing Python binding code for a C++ function:

void cls::acceptCall(My::namespace::Reply reply)
{
    std::cout <<__FUNCTION__ << std::endl;
    reply(My::namespace::Result::Ok, nullptr);
}
using Reply = std::function<void(Result result, std::exception_ptr error)>;
enum class Result {Ok,NOT_OK }

bind code:

py::class_<APIExtProvider>(m, "APIExtProvider")
    .def("acceptCall", &APIExtProvider::acceptCall, py::call_guard<py::gil_scoped_release>())

python_call:

result = pyunifiedphone.Result.OK
exception = pyunifiedphone.Exception()

def reply_method(result, exception):
    return None
     
 provider.acceptCall(reply_method)

However, I get this error:

TypeError: acceptCall(): incompatible function arguments. The following argument types are supported:
1. (self: pyunifiedphone.APIExtProvider, arg1: Callable[[pyunifiedphone.Result, pyunifiedphone.Exception], None]) -> None

Invoked with: <pyunifiedphone.APIExtProvider object at 0x7f2b6aa149b0>, , <function reply_method at 0x7f2b6abfa1f0>

What is the correct way of binding?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

美煞众生 2025-02-20 04:37:21

不幸的是,PYBIND11不会自动将数据类型从C/C ++转换为Python。
将此标头文件添加到您的项目中,然后再次测试。如果它不起作用,则应将数据转换为可约束类型。

#include <pybind11/functional.h>
#include <pybind11/chrono.h>
#include <pybind11/stl.h>
#include <pybind11/complex.h>

unfortunately pybind11 does not auto convert data types from c/c++ to python .
add this header files to your project and test again . if it did not work , you should convert your data to a bindable type .

#include <pybind11/functional.h>
#include <pybind11/chrono.h>
#include <pybind11/stl.h>
#include <pybind11/complex.h>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文