我使用c ++来控制python 2.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
class cppMethods():
def getSum(self, a):
print("This line will be printed.");
print("a=",a);
number = a + 3;
print("number=",number);
return number;
答案 0 :(得分:0)
用于PyObject_CallMethod
的格式字符串应该产生一个元组。 You need to parenthesize the string contents当只有一个值时强制一个元组:
PyObject_CallMethod(instance, "getSum", "(i)", 5)
答案 1 :(得分:0)
这是怎么回事:
object module = import("cppMethods");
object _class = module.attr("cppMethods")();
auto res = _class.attr("getSum")(5);
int x = extract<int>(res);