【问题标题】:Python C++ API function with multiple arguments具有多个参数的 Python C++ API 函数
【发布时间】:2022-11-28 16:07:48
【问题描述】:

我正在尝试使用我的 C++ 代码创建一个 python 模块,我想声明一个具有多个参数的函数。 (在这种情况下为 3)我已经阅读了文档,它说我必须声明 METH_VARARGS 我做了,但我认为我还必须更改函数内部的某些内容以实际接收参数。否则,当我在 python 中使用我的函数时,它会给我“太多参数”错误。

这是我正在使用的代码 sn-p:

...
// This function can be called inside a python file.
static PyObject *
call_opencl(PyObject *self, PyObject *args)
{
    const char *command;
    int sts;

    // We except at least one argument to this function
    // Not sure how to accept more than one.
    if (!PyArg_ParseTuple(args, "s", &command))
        return NULL;

    OpenCL kernel = OpenCL();
    kernel.init();

    std::cout << "This message is called from our C code: " << std::string(command) << std::endl;

    sts = 21;

    return PyLong_FromLong(sts);
}

static PyMethodDef NervebloxMethods[] = {
    {"call_kernel",          call_opencl,         METH_VARARGS,              "Creates an opencv instance."},
    {NULL, NULL, 0, NULL}        /* Sentinel */
};

...

【问题讨论】:

    标签: python c++ python-3.x


    【解决方案1】:

    你仍然期待一个论点。

    if (!PyArg_ParseTuple(args, "s", &command))
    

    documentation 定义了您如何期望可选或附加参数,例如“s|dd”将期望一个字符串和两个可选数字,您仍然必须将两个双精度数传递给函数,以便在数字可用时使用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-10
      • 2019-07-18
      • 1970-01-01
      • 1970-01-01
      • 2017-10-05
      • 2013-03-06
      • 1970-01-01
      相关资源
      最近更新 更多