【问题标题】:Python C Api check if PyObject points to a specific PyCFunctionPython C Api 检查 PyObject 是否指向特定的 PyCFunction
【发布时间】:2021-02-20 17:34:17
【问题描述】:

我有一个使用 Python C API 编写的模块:

static PyObject* my_func1(PyObject* /*self*/, PyObject* args)
{
  Py_RETURN_NONE;
}

static PyObject* my_func2(PyObject* /*self*/, PyObject* args)
{
  Py_RETURN_NONE;
}


static PyMethodDef methods[] = {
    {"my_func1", (PyCFunction)my_func1, METH_VARARGS, ""}, 
    {"my_func2", (PyCFunction)my_func2, METH_VARARGS, ""},
    {NULL, NULL, 0, NULL} /* sentinel */
};

static struct PyModuleDef moduledef = {                                                          
      PyModuleDef_HEAD_INIT, my_module, NULL, -1, methods, NULL, NULL, NULL, NULL
};                     
 
PyMODINIT_FUNC PyInit_my_module(void){                                                                                                
    return PyModule_Create(&moduledef);                                                            
}

作为用户可以传递函数的参数之一,例如:

my_func1(my_func2)

如何使用 Python C API 在my_func1 内部检测到用户传递的参数是一个指向my_func2 的函数?

【问题讨论】:

    标签: python c python-3.x python-c-api


    【解决方案1】:

    您可以使用PyCFunction_Check 来测试对象是否是C 函数,并使用PyCFunction_GetFunction 来获取C 函数指针。然后,您可以只比较 C 函数指针。如果您想查看签名,相关标题位于https://github.com/python/cpython/blob/4c9ea093cd752a6687864674d34250653653f743/Include/methodobject.h

    这看起来至少可以追溯到 Python 3.6(可能更远),虽然有点难以跟踪,因为他们已经移动了一些定义的标头。

    请注意,这一切看起来都没有记录,所以你不应该完全依赖它不改变。

    【讨论】:

    • 谢谢,这正是我正在寻找的。请注意,这在 python2.7 和 python3.5 中也适用于我
    猜你喜欢
    • 1970-01-01
    • 2012-08-10
    • 2023-03-02
    • 2016-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多