Commits

Vertexwahn committed 17388b9

EmbeddedPython: Started refactoring.

Comments (0)

Files changed (1)

EmbeddedPython/main.cpp

 int	main(int argc, char *argv4356[])
 {
 	// multiply multiply 3 2
-	argc = 5;
-	char *argv[5];
-	argv[1] = "multiply";
-	argv[2] = "multiply";
-	argv[3] = "3";
-	argv[4] = "2";
 
-	PyObject *pName, *pModule, *pDict, *pFunc;
+	char* moduleName = "multiply";
+	char* functionName = "multiply";
+	char* arguments[2];
+	arguments[0] = "3";
+	arguments[1] = "2";
+
+	PyObject *pModule, *pDict, *pFunc;
 	PyObject *pArgs, *pValue;
 	int i;
 
 	Py_Initialize();
-	pName = PyUnicode_FromString(argv[1]);
-	/* Error checking of pName left out */
+	PyObject *pName = PyUnicode_FromString(moduleName);
+	// Error checking of pName left out
 
 	pModule = PyImport_Import(pName);
 	Py_DECREF(pName);
 
 	if (pModule != nullptr) 
 	{
-		pFunc = PyObject_GetAttrString(pModule, argv[2]);
-		/* pFunc is a new reference */
+		pFunc = PyObject_GetAttrString(pModule, functionName);
+		// pFunc is a new reference
 
 		if (pFunc && PyCallable_Check(pFunc)) 
 		{
-			pArgs = PyTuple_New(argc - 3);
-			for (i = 0; i < argc - 3; ++i) 
+			pArgs = PyTuple_New(2);
+
+			for (i = 0; i < 2; ++i) 
 			{
-				pValue = PyLong_FromLong(atoi(argv[i + 3]));
+				pValue = PyLong_FromLong(atoi(arguments[i]));
 				if (!pValue) 
 				{
 					Py_DECREF(pArgs);
 					Py_DECREF(pModule);
-					fprintf(stderr, "Cannot convert argument\n");
+					std::cout << "Cannot convert argument" << std::endl;
 					return 1;
 				}
-				/* pValue reference stolen here: */
+				// pValue reference stolen here:
 				PyTuple_SetItem(pArgs, i, pValue);
 			}
+
 			pValue = PyObject_CallObject(pFunc, pArgs);
 			Py_DECREF(pArgs);
+
 			if (pValue != nullptr)
 			{
 				printf("Result of call: %ld\n", PyLong_AsLong(pValue));
 				Py_DECREF(pFunc);
 				Py_DECREF(pModule);
 				PyErr_Print();
-				fprintf(stderr,"Call failed\n");
+				std::cout << "Call failed" << std::endl;
 				return 1;
 			}
 		}
 		{
 			if (PyErr_Occurred())
 				PyErr_Print();
-			fprintf(stderr, "Cannot find function \"%s\"\n", argv[2]);
+
+			std::cout << "Cannot find function \"" << functionName << "\"" << std::endl;
 		}
+
 		Py_XDECREF(pFunc);
 		Py_DECREF(pModule);
 	}
 	else
 	{
 		PyErr_Print();
-		fprintf(stderr, "Failed to load \"%s\"\n", argv[1]);
+
+		std::cout << "Failed to load \"" << moduleName << "\"" << std::endl;
 		return 1;
 	}
+
 	Py_Finalize();
 	return 0;
 }