PyObject_CallMethod返回1

2024-09-29 19:19:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用c++控制Python2.7,但是调用该方法并没有返回正确的值。此外,方法得到的不是参数5,而是1—为什么会这样?在

PyObject * ws = PyImport_ImportModule("cppMethods"); //cppMethods.py
PyObject* klass = PyObject_GetAttrString(ws, "cppMethods"); //class
PyObject* instance = PyInstance_New(klass, NULL, NULL);
//call_method<int>(instance, "getSum", 1);
PyObject* result = PyObject_CallMethod(instance, "getSum", "i", 5);
auto res3 = PyInt_AsLong(result); //-1 here

^{pr2}$

Tags: 方法instancepy参数wsresultnullclass
2条回答

一切都是这样的:

object module = import("cppMethods");
object _class = module.attr("cppMethods")();
auto res = _class.attr("getSum")(5);
int x = extract<int>(res);

用于PyObject_CallMethod的格式字符串应生成元组。You need to parenthesize the string contents在只有一个值时强制执行元组:

PyObject_CallMethod(instance, "getSum", "(i)", 5)

相关问题 更多 >

    热门问题