python - 无法在 pybind11 中绑定(bind)重载的静态成员函数

标签 python c++ function-pointers pointer-to-member pybind11

我尝试用 pybind11 绑定(bind)静态重载函数,但遇到了一些问题。

这是示例代码

#include <pybind11/pybind11.h>

namespace py = pybind11;

class TESTDB {
  public:
    static void aaaa(int a, int b) {printf("aaaaa");};
    static void aaaa(int a) {printf("xxxxx");};
};

PYBIND11_MODULE(example, m) {


  py::class_<TESTDB>(m, "db")
     .def_static("aaaa", (void (TESTDB::*)(int, int)) &TESTDB::aaaa);

}

但是编译失败是因为

error: no matches converting function ‘aaaa’ to type ‘void (class TESTDB::*)(int, int)’
   .def_static("aaaa", (void (TESTDB::*)(int, int)) &TESTDB::aaaa);
 note: candidates are: static void TESTDB::aaaa(int)
 static void aaaa(int a) {printf("xxxxx");};
 note:                 static void TESTDB::aaaa(int, int)
 static void aaaa(int a, int b) {printf("aaaaa");};

有什么想法吗?

谢谢

最佳答案

问题是你的转换 (void (TESTDB::*)(int, int))。该转换将指向静态成员函数的指针转换为指向-静态成员函数的指针,这是不正确的。

由于函数是静态的,您应该简单地将它们转换为指向普通非成员函数的指针:

py::class_<TESTDB>(m, "db")
    .def_static("aaaa", static_cast<void (*)(int, int)>(&TESTDB::aaaa));

关于python - 无法在 pybind11 中绑定(bind)重载的静态成员函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55613577/

相关文章:

c++ - 如何在类 vector 中存储/使用外部函数指针

c - 学习集 : How do I place the asterisks and ampersands on function arguments and function calls?

python - 如何使用tornado python将用户输入数据保存到redis

C++ 引用和引用参数

c++ - 一个全局对象是如何在它被声明为 const 之前构造的?

c++ - 指向成员函数的奇怪方式

python正则表达式在字符的最后两次出现之间保留文本

python - 如何使用 sympy 在 python 中查找函数的域

python - 从 2D numpy 数组中删除运行

c++ - 将 C++ (qt) 程序构建为一个具有内置依赖项的可移植文件