2

如果我试图重载嵌入式 Python 函数,以便第二个参数可以是 long 或 Object,是否有标准的方法来做到这一点?是这个吗?

我现在正在尝试的(更改名称以保护无辜者):

  bool UseLongVar2 = true;
  if (!PyArg_ParseTuple(args, "ll:foo", &LongVar1, &LongVar2))
  {
      PyErr_Clear();
      if (!PyArg_ParseTuple(args, "lO&:foo", &LongVar1, convertObject, &Object))
      {
         UseLongVar2 = false;
         return NULL;
      }
  }
4

1 回答 1

3

What I normally do is have two C functions that take the different arguments. The "python-facing" function's job is to parse out the arguments, call the appropriate C function, and build the return value if any.

This is pretty common when, for example, you want to allow both byte and Unicode strings.

Here is an example of what I mean.

// Silly example: get the length of a string, supporting Unicode and byte strings
static PyObject* getlen_py(PyObject *self, PyObject *args)
{
    // Unpack our argument (error handling omitted...)
    PyObject *arg = NULL;
    PyArg_UnpackTuple(args, "getlen", 1, 1, arg) ;

    if ( PyUnicode_Check(arg) )
    {
        // It's a Unicode string
        return PyInt_FromLong(getlen_w(PyUnicode_AS_UNICODE(arg))) ;
    }
    else
    {
        // It's a byte string
        return PyInt_FromLong(getlen_a(PyString_AS_STRING(arg))) ;
    }
}
于 2010-02-18T23:14:11.870 回答