// SnakesTest.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include static int numargs = 0; /* Return the number of arguments of the application command line */ static PyObject* emb_numargs(PyObject *self, PyObject *args) { if (!PyArg_ParseTuple(args, ":numargs")) return NULL; return PyLong_FromLong(numargs); } static PyMethodDef EmbMethods[] = { { "numargs", emb_numargs, METH_VARARGS, "Return the number of arguments received by the process." }, {NULL, NULL, 0, NULL} }; static PyModuleDef EmbModule = { PyModuleDef_HEAD_INIT, "emb", NULL, -1, EmbMethods, NULL, NULL, NULL, NULL }; static PyObject* PyInit_emb(void) { return PyModule_Create(&EmbModule); } void PrintTotalRefCount() { #ifdef Py_REF_DEBUG PyObject* refCount = PyObject_CallObject(PySys_GetObject((char*)"gettotalrefcount"), NULL); std::clog << "total refcount = " << PyInt_AsSsize_t(refCount) << std::endl; Py_XDECREF(refCount); #endif } // *************************************************************** int main(int argc, char *argv[]) { PyObject *pName, *pModule, *pFunc; // *pDict, ; PyObject *pArgs, *pValue; if (argc < 3) { fprintf(stderr, "Usage: call pythonfile funcname [args]\n"); return 1; } numargs = argc; PyImport_AppendInittab("emb", &PyInit_emb); //Py_SetPath(L"python_lib.zip;_scripts.dat"); Py_SetPath(L"pyLib34.zip"); wchar_t* pyPath = Py_GetPath(); // Some info parameters const char* pyVersion = Py_GetVersion(); const char* pyOS = Py_GetPlatform(); const char* pyBuildInfo = Py_GetBuildInfo(); const char* pyCompiler = Py_GetCompiler(); Py_Initialize(); pName = PyUnicode_FromString(argv[1]); /* Error checking of pName left out */ pModule = PyImport_Import(pName); Py_XDECREF(pName); if (pModule != NULL) { pFunc = PyObject_GetAttrString(pModule, argv[2]); /* pFunc is a new reference */ int i; printf("***Test1"); if (pFunc && PyCallable_Check(pFunc)) { printf("***Test2"); pArgs = PyTuple_New(argc - 3); for (i = 0; i < argc - 3; ++i) { pValue = PyLong_FromLong(atoi(argv[i + 3])); if (!pValue) { Py_XDECREF(pArgs); Py_XDECREF(pModule); fprintf(stderr, "Cannot convert argument\n"); return 1; } /* pValue reference stolen here: */ PyTuple_SetItem(pArgs, i, pValue); } printf("***Test3"); pValue = PyObject_CallObject(pFunc, pArgs); printf("***Test4"); Py_XDECREF(pArgs); if (pValue != NULL) { printf("Result of call: %ld\n", PyLong_AsLong(pValue)); Py_XDECREF(pValue); } else { Py_XDECREF(pFunc); Py_XDECREF(pModule); PyErr_Print(); fprintf(stderr, "Call failed\n"); return 1; } } else { if (PyErr_Occurred()) PyErr_Print(); fprintf(stderr, "Cannot find function \"%s\"\n", argv[2]); } Py_XDECREF(pFunc); Py_XDECREF(pModule); } else { PyErr_Print(); fprintf(stderr, "Failed to load \"%s\"\n", argv[1]); return 1; } printf("***Test5"); Py_Finalize(); PrintTotalRefCount(); return 0; }