从C++中找到Python函数参数

4 投票
1 回答
2167 浏览
提问于 2025-04-16 21:03

我在用C++调用Python函数。我想知道有没有办法确定这些函数的参数数量和参数名称。我看过这个链接如何从C中找到Python函数的参数数量?,但是我不是很理解。

我有一个C++函数,它调用了pyFunction.py中的'add'函数。'add'函数需要两个参数,并返回它们的和。

static float CallPythonFunc( float *parameters )
{
    PyObject *pName, *pModule, *pDict, *pFunc, *pValue, *pArgs;
    float ret;

    // Initialize the python interpreter
    Py_Initialize();

    // Make sure we are getting the module from the correct place
    // ### This is where we will put the path input
    PyRun_SimpleString("import sys");
    PyRun_SimpleString("sys.path.append(\"/Developer/IsadoraSDK/IsadoraDemoMathFunction/\")");

    // Build the name object
    // ### This is where we will put the function input
    pName = PyString_FromString("pyFunction");

    // Load the module object
    pModule = PyImport_Import(pName);

    // pDict is a borrowed reference
    pDict = PyModule_GetDict(pModule);

    // pFunc is a borrowed reference
    pFunc = PyDict_GetItemString(pDict, "add");

    //
    // Somehow get the number of arguments and possible the arguments names from 'add'
    //

    if (PyCallable_Check(pFunc)) 
    {       
        // Set the number of arguments
                // This is where I would like to pass in number of arguments
        pArgs = PyTuple_New( 2 /*number of arguments*/ );

        //
        // Instead of the following if I had the arguments I could loop through them
        // and pass the correct number in
        //

        // Argument 1
        pValue = PyFloat_FromDouble((double)parameters[0]);
        PyTuple_SetItem(pArgs, 0, pValue);

        // Argument 2
        pValue = PyFloat_FromDouble((double)parameters[1]);
        PyTuple_SetItem(pArgs, 1, pValue);

            // Make the call to the function
        pValue = PyObject_CallObject(pFunc, pArgs);

        // Set return value
        ret = (float)PyFloat_AsDouble(pValue);

        // Clean up
        Py_DECREF(pArgs);
        Py_DECREF(pValue);
    }

// Clean up
Py_DECREF(pModule);
Py_DECREF(pName);

// Finish the Python Interpreter
Py_Finalize();

return ret;
}

我对C/C++不是很熟悉,所以任何帮助都非常感谢。谢谢大家的时间!

编辑:那像下面这样可以吗?

PyObject *tuple, *arglist;
tuple = PyObject_CallMethod(pFunc,"inspect.getargspec","add");
arglist = PyTuple_GetItem(tuple,0);
int size = PyObject_Size(arglist);

1 个回答

5

你链接的那个问题的答案似乎正是你需要的。inspect.getargspec 在 Python 里可以完美地完成你想要的事情。正如答案中提到的,你可以使用 PyObject_CallMethod 或者那个链接里提到的相关函数,从你的 C++ 代码中调用 inspect.getargspec。这样你就能得到一个返回的元组,作为 PyObject 使用。接着,你可以用 PyTuple_GetItem(returned_tuple, 0) 来获取参数列表,然后用 PyObject_Size()PyObject_Length() 来获取参数的数量。此外,你还需要检查返回的元组中的第二和第三个元素,如果这两个元素不是 Py_None,就把参数数量加 1。下面的代码片段会解释为什么要这样做。

>>> import inspect
>>> def testfunc(a, b, c, *d, **e):
    pass

>>> inspect.getargspec(testfunc)
ArgSpec(args=['a', 'b', 'c'], varargs='d', keywords='e', defaults=None)

下面是你应该怎么做的一个例子(虽然可能没有检查所有可能的错误,但至少应该包含所有必要的 NULL 检查):

PyObject *pName, *pInspect, *argspec_tuple, *arglist;
int size;

pName = PyString_FromString("inspect");

if (pName)
{
    pInspect = PyImport_Import(pName);
    Py_DECREF(pName);


    if (pInspect)
    {
        pName = PyString_FromString("getargspec");

        if (pName)
        {
            argspec_tuple = PyObject_CallMethodObjArgs(pInspect, pName, pFunc, NULL);
            Py_DECREF(pName);

            if (argspec_tuple)
            {
                arglist = PyTuple_GetItem(argspec_tuple, 0);

                if (arglist)
                {
                    size = PyObject_Size(arglist)
                         + (PyTuple_GetItem(argspec_tuple, 1) == Py_None ? 0 : 1)
                         + (PyTuple_GetItem(argspec_tuple, 2) == Py_None ? 0 : 1);  // Haven't actually tested this, but it should work
                }
            }
        }
    }
}

撰写回答