(original) (raw)
Hello,I am trying to send a tuple to a method of a python class and I got a Run failed from netbeans compiler
when I want to send a tuple to a simple method in a module it works,when I want to send a simple parameter to a method of a clas it works also but not a tuple to a method of a class
I put the code below,thanks for all the possible suggestions
Python Code:
class cVector:
def \_\_init\_\_(self,msg):
self.value = msg
def ComputeNorm(self,vecData):
#don't use vecData for instance
result = 12.
return(result)
C++ Code :
PyObject \*ret, \*mymod, \*pclass, \*method, \*args, \*object;
float retValue;
Py\_Initialize();
//PySys\_SetPath("/home/pascal/projPytCpp/proj1");
PySys\_SetPath(".");
// Module
mymod = PyImport\_ImportModule("mModule8");
if (mymod == NULL){
cout << "Can't Open a module:\\n" ;
Py\_DECREF(mymod);
}
// Class
pclass = PyObject\_GetAttrString(mymod, "cVector");
if (pclass == NULL) {
Py\_DECREF(pclass);
cout << "Can't find class\\n";
}
// Parameters/Values
args = Py\_BuildValue("(f)", 100.0);
if (args == NULL) {
Py\_DECREF(args);
cout << "Can't build argument list for class instance\\n";
}
// Object with parameter/value
object = PyEval\_CallObject(pclass, args);
if (object == NULL) {
Py\_DECREF(object);
cout << "Can't create object instance:\\n";
}
// Decrement the argument counter as we'll be using this again
Py\_DECREF(args);
// Get the object method - note we use the object as the object
// from which we access the attribute by name, not the class
method = PyObject\_GetAttrString(object, "ComputeNorm");
if (method == NULL) {
Py\_DECREF(method);
cout << "Can't find method\\n";
}
// Decrement the counter for our object, since we now just need
// the method reference
Py\_DECREF(object);
// Build our argument list - an empty tuple because there aren't
// any arguments
cout << "Prepare the Tuple:\\n" ;
// WE pass a tuple
args = PyTuple\_New( 3 );
if (args == NULL) {
Py\_DECREF(args);
cout << "Can't build argument list for method call\\n";
}
PyObject \*py\_argument;
// 1st argument
py\_argument = PyFloat\_FromDouble(5.);
PyTuple\_SetItem(args, 0, py\_argument);
// 2nd argument
py\_argument = PyFloat\_FromDouble(10.);
PyTuple\_SetItem(args, 1, py\_argument);
// 3nd argument
py\_argument = PyFloat\_FromDouble(15.);
PyTuple\_SetItem(args, 2, py\_argument);
cout << "Before the Exec:\\n" ;
// Call our object method with arguments (try two ways to do it any works)
//ret = PyEval\_CallObject(method,args);
ret = PyObject\_CallObject(method,args);
if (ret == NULL) {
Py\_DECREF(ret);
cout << "Couldn't call method\\n";
}
// Convert the return value back into a C variable and display it
PyArg\_Parse(ret, "f", &retValue);
printf("Farenheit: %f\\n", retValue);
// Kill the remaining objects we don't need
Py\_DECREF(method);
Py\_DECREF(ret);
// Close off the interpreter and terminate
Py\_Finalize();