python - 在对象上调用方法

标签 python c embedded-language

给定一个指向 python 对象的 PyObject*,我如何调用其中一个对象方法?文档从未给出这样的例子:

PyObject* obj = ....
PyObject* args = Py_BuildValue("(s)", "An arg");
PyObject* method = PyWHATGOESHERE(obj, "foo");
PyObject* ret = PyWHATGOESHERE(obj, method, args);
if (!ret) {
   // check error...
}

这相当于

>>> ret = obj.foo("An arg")

最佳答案

PyObject* obj = ....
PyObject *ret = PyObject_CallMethod(obj, "foo", "(s)", "An arg");
if (!ret) {
   // check error...
}

阅读 Python C API documentation .在这种情况下,您需要 object protocol .

PyObject* PyObject_CallMethod(PyObject *o, char *method, char *format, ...)

Return value: New reference.

Call the method named method of object o with a variable number of C arguments. The C arguments are described by a Py_BuildValue() format string that should produce a tuple. The format may be NULL, indicating that no arguments are provided. Returns the result of the call on success, or NULL on failure. This is the equivalent of the Python expression o.method(args). Note that if you only pass PyObject * args, PyObject_CallMethodObjArgs() is a faster alternative.

PyObject* PyObject_CallMethodObjArgs(PyObject *o, PyObject *name, ..., NULL)

Return value: New reference.

Calls a method of the object o, where the name of the method is given as a Python string object in name. It is called with a variable number of PyObject* arguments. The arguments are provided as a variable number of parameters followed by NULL. Returns the result of the call on success, or NULL on failure.

关于python - 在对象上调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1364117/

相关文章:

python - 我可以使用 zipimport 来发送嵌入式 python 吗?

python - python/scikit-learn 中距离计算的稀疏实现

Python 新手合并文本

C 编程数据类型

python - 嵌入 C 时维护 Python 对象

PHP:是否有可能以某种方式将 HTML 嵌入到三元运算符的中间?

python - 在 matplotlib 中将 Y 轴的标题旋转为水平

Python Tkinter : Listbox mouse enter event for a specific entry

c - 不使用指针的堆栈实现

C编程二维数组内存布局