Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: C++ C Python
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);
	//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 21-Mar-13 9:24am

1 solution

Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

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
  Permalink  

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

  Print Answers RSS
0 OriginalGriff 304
1 Sergey Alexandrovich Kryukov 255
2 Maciej Los 250
3 Shweta N Mishra 216
4 PIEBALDconsult 174
0 OriginalGriff 7,660
1 Sergey Alexandrovich Kryukov 7,072
2 DamithSL 5,586
3 Manas Bhardwaj 4,946
4 Maciej Los 4,665


Advertise | Privacy | Mobile
Web03 | 2.8.1411023.1 | Last Updated 21 Mar 2013
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100