I'm currently using the following code to access my Python files via C++:
std::string Main(std::string url)
{
char* paras[] = {"4", "5"};
Py_Arg("test", "multiply", paras);
return "";
}
int Py_Arg(char* fileName, char* funcName, char* args[])
{
PyObject *pName, *pMod, *pDict, *pFunc, *pVal;
Py_Initialize();
pName = PyString_FromString(fileName);
pMod = PyImport_Import(pName);
pDict = PyModule_GetDict(pMod);
pFunc = PyDict_GetItemString(pDict, funcName);
int argc = std::strlen((char*)args);
if(PyCallable_Check(pFunc))
{
PyObject *pArgs = PyTuple_New(argc - 1);
for(int i = 0 ; i <= argc - 1; i++)
{
pVal = PyInt_FromLong(atoi(args[i]));
if(!pVal)
{
PyErr_Print();
return 1;
}
PyTuple_SetItem(pArgs, i, pVal);
}
pVal = PyObject_CallObject(pFunc, pArgs);
if(pArgs != NULL)
{
Py_DECREF(pArgs);
}
if(pVal != NULL)
{
std::printf("Return of call: %d\n", PyInt_AsLong(pVal));
Py_DECREF(pVal);
}
else
{
PyErr_Print();
}
}
else
{
PyErr_Print();
}
Py_DECREF(pMod);
Py_DECREF(pName);
Py_Finalize();
return 0;
}
And here is the Python code:
def multiply(num1, num2):
c = num1 * num2
print 'The result is:', c
return
Everything works fine. However, now I want the code to return an integer product instead of just printing it. Yet the second I add "return c" to the end of my Python code, I get the following error in Visual Studio (2010):
Microsoft Visual Studio C Runtime Library has detected a fatal error in FunctTest.exe.
Press Break to debug the program or Continue to terminate the program.
How can I have the function return a value to my C++ app? I know it will involve conversion using the API, but I have no idea where to start. The tutorials I followed online still gave me this error. Any help would be appreciated. Thanks in advance!