[英]CPython 'overloaded' functions
我正在尝试重载一个接受对象或字符串的 python 扩展函数。
typedef struct
{
PyObject_HEAD
} CustomObject;
PyObject* customFunction(CustomObject* self, PyObject* args);
PyMethodDef methods[] =
{
{"customFunction", (PyCFunction) customFunction, METH_VARAGS, "A custom function"},
{NULL}
}
PyTypeObject TypeObj =
{
PyVarObject_HEAD_INIT(NULL, 0)
.tp_name = "customModule.CustomObject",
.tp_doc = "Custom Object",
.tp_basicsize = sizeof(CustomObject),
.tp_itemsize = 0,
.tp_flags = Py_TPFLAGS_DEFAULT,
.tp_methods = methods,
}
// Area of problem
PyObject* customFunction(CustomObject* self, PyObject* args)
{
const char* string;
PyObject* object;
if (PyArg_ParseTuple(args, "O!", &TypeObj, &object)) // TypeObj is the PyTypeObject fpr CustomObject
{
std::cout << "Object function\n"
// Do whatever and return PyObject*
}
else if (PyArg_ParseTuple(args, "s", &string))
{
std::cout << "String function\n"
// Do whatever and return PyObject*
}
return PyLong_FromLong(0); // In case nothing above works
}
在 python 中,除了函数之外,我尝试了这个错误Error: <built-in method customFunction of CustomModule.CustomObject object at 0xmemoryadress> returned a result with an error set
以下是此 PyArg_ParseTuple 的 Python 文档:
int PyArg_ParseTuple(PyObject *args, const char *format, ...)
解析仅将位置参数转换为局部变量的函数的参数。 成功返回真; 失败时,它返回 false 并引发适当的异常
我猜测 PyArg_ParseTuple 设置了一个错误,这导致整个函数无法工作(我的模块方法表中确实有 customFunction,我只是省略了该代码)。 如果我有以下 Python:
import CustomModule
try:
CustomModule.customFunction("foo")
except Exception as e:
print("Error:", e)
String function
确实被输出,所以字符串 if 语句中的代码确实有效,但我假设错误发生是因为对象的 PyArg_ParseTuple 失败,所以它返回一个错误(不是 100% 确定这是否正确)。
有没有办法可以防止 PyArg_ParseTuple() 引发错误,是否有其他函数,或者是否有更好的方法来“重载”我的自定义函数?
我可能只是使用PyArg_ParseTuple
来获取通用的未指定对象,然后稍后使用Py*_Check
处理对象类型:
if (!PyArg_ParseTuple(args, "O", &object)) {
return NULL;
}
if (PyObject_IsInstance(object, (PyObject*)&PyType)) { // or a more specific function if one exists
std::cout << "Object function\n";
} else if (PyUnicode_Check(object)) {
std::cout << "String function\n";
} else {
// set an error, return NULL
}
这样做的原因是 Python 的“请求宽恕,而不是许可”模式
try:
something()
except SomeException:
somethingElse()
不能很好地转换为 C,并且涉及相当多的代码来处理异常。 如果你真的想这样做的,那么你需要调用PyErr_Clear
第二前PyArg_ParseTuple
,理想情况下,你应该检查它的你认为是例外,而且不完全是另一回事。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.