我使用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)
我如何在my_func1
内部检测到用户传递的参数是一个函数,它使用pythoncapi指向my_func2
您可以使用
PyCFunction_Check
测试对象是否为C函数,并使用PyCFunction_GetFunction
获取C函数指针。然后就可以比较C函数指针了。如果您想查看签名,则相关标头位于https://github.com/python/cpython/blob/4c9ea093cd752a6687864674d34250653653f743/Include/methodobject.h这看起来至少可以追溯到Python3.6(可能更久远),尽管跟踪起来有点困难,因为他们在一点时间内移动了定义的标题
请注意,这一切看起来都相当没有文档记录,所以您不应该完全依赖它,因为它不会改变
相关问题 更多 >
编程相关推荐