Click here to Skip to main content
15,888,286 members
Please Sign up or sign in to vote.
2.50/5 (2 votes)
See more:
I'm currently using the following code to access my Python files via C++:

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);
	//std::cout << "!" << argc;
	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!
Posted

1 solution

I am not a python pro but my understanding is that it should work as you suggest. Also, according to the docs:

def multiply(num1, num2):
    multiply = num1 * num2

and
def multiply(num1, num2):
    return num1 * num2
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900