简体   繁体   English

使用多个函数参数调用PyObject_CallObject

[英]Call PyObject_CallObject with more than one function argument

If I have a function in Python like this: 如果我在Python中有这样的函数:

def multiply(a, b)
    return a * b

How can I call PyObject_CallObject when it will give me an error if I have more than two arguments? 如果我有两个以上的参数,如何给我一个错误,我该如何调用PyObject_CallObject There may be a much better way of calling a function from C++ but I am very new to the Python/C API 从C ++调用函数可能有更好的方法,但是我对Python / C API还是很陌生

From the documentation : 文档中

PyObject* PyObject_CallObject(PyObject *callable_object, PyObject *args)

Return value: New reference. 返回值:新参考。

Call a callable Python object callable_object , with arguments given by the tuple args . 调用可调用的Python对象callable_object ,其参数由元组args给出 If no arguments are needed, then args may be NULL . 如果不需要参数,则args可以为NULL Returns the result of the call on success, or NULL on failure. 如果成功,则返回调用结果;如果失败,则返回NULL This is the equivalent of the Python expression callable_object(*args) . 这等效于Python表达式callable_object(*args)

In other words: 换一种说法:

  • You can pass more than one argument to the function by passing a single tuple containing the arguments. 您可以通过传递一个包含参数的tuple来将多个参数传递给函数。 So you'd have to build a tuple containing x and y (ie (x, y) ) and then pass the tuple as single parameter to PyObject_CallObject(multiply, the_tuple) this will be equivalent to multiply(x, y) . 所以,你必须建立一个tuple包含xy (即(x, y)然后元组作为单一参数传递给PyObject_CallObject(multiply, the_tuple)这将相当于multiply(x, y)
  • It does not represent the most general call. 并不代表最一般的呼叫。 The most generic call is PyObject_Call which takes two arguments: a tuple of positional arguments and a dictionary of keyword arguments. 最通用的调用是PyObject_Call ,它带有两个参数:位置参数的元组和关键字参数的字典。
  • There are also the PyObject_CallFunction* functions that are similar to PyObject_CallObject but they avoid having to create the tuple and allow multiple parameters. 还有一些PyObject_CallFunction*函数与PyObject_CallObject类似,但它们避免了创建元组并允许多个参数的麻烦。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM