Python C++ api - return 函数重载中的不同类型

Python C++ api - return different types in function overloading

我有一个 C++ class,其中包含两个重载方法 sayHi(),每个方法都有不同的 return 类型:

class Box {
   public:

      Box();

      void sayHi(char *name);

      int sayHi(int number);

};

当我尝试包装这个函数时,我遵循了 的建议并且 "write a single wrapper function that type checks the argument provided and dispatches to the correct 'real' function".

这里是:

static PyObject *pyBox_sayHi_char(PyBox *self, char *Name)
{
    self->bx->sayHi(Name);

    Py_RETURN_NONE;
}

static int *pyBox_sayHi_int(PyBox *self,  int number)
{
    int answer;

    answer = self->bx->sayHi(number);

    return answer;
}

static PyObject *Hi_overload_switch(PyBox *self,  PyObject *args)
{
    PyObject *x;

    if (!PyArg_ParseTuple(args, "O", &x))
        return NULL;

    if (PyUnicode_Check(x))
    {
        const char* s = PyBytes_AsString(PyUnicode_AsUTF8String(x)); // convert PyObject to char*

        Py_DECREF(x);

        return pyBox_sayHi_char(self, s);
    }
    if (PyLong_Check(x))
    {   
        return pyBox_sayHi_int( self, PyLong_AsLong(x) );
    }
    Py_RETURN_NOTIMPLEMENTED;
}

和以下方法table:

static PyMethodDef pyBox_methods[] = {
    {"Hi", (PyCFunction)Hi_overload_switch, METH_VARARGS, "Hi"},
    {NULL, NULL, 0, NULL}
};

但是,我收到错误消息:

error: cannot convert ‘int*’ to ‘PyObject*’ {aka ‘_object*’} in return
         return pyBox_sayHi_int( self, PyLong_AsLong(x) );

AFAIK,我不想将 return 类型转换为 PyObjects,因为重载方法可能需要 return 自定义类型。因此,我示例中的 intvoid 仅用于说明目的——我可能会写成 PyBanana vs PyOrange 数据类型。

我的问题是,如何使函数 Hi_overload_switch return 不同类型?

谢谢!

你需要return一个Pythonint。在 C/C++ 源代码中,这是一个 PyLongObject (Which is a subtype of PyObject, so you can cast a PyLongObject* to a PyObject* and back). To convert a C++ int into a PyObject* Python int, use PyObject* PyLong_FromLong(long):

static PyObject *pyBox_sayHi_int(PyBox *self,  int number)
{
    int answer;

    answer = self->bx->sayHi(number);

    return PyLong_FromLong(answer);
}