L
lipingffeng
Hi, all,
I am currently involved in a project that needs to load/run a python
script dynamically in a C application. The sample code is as
following:
PyObject *LoadScript(char *file, char *func)
{
PyObject *pName, *pModule, *pDict, *pFunc;
pName = PyString_FromString(file);
pModule = PyImport_Import(pName);
pDict = PyModule_GetDict(pModule);
pFunc = PyDict_GetItemString(pDict, func);
return pFunc;
}
int RunScript(PyObject *pFunc, PyObject *arglist)
{
PyObject *pValue = PyObject_CallFunction(pFunc, "O", arglist);
int ret = PyInt_AsLong(pValue);
return ret;
}
int main(int argc, char *argv[])
{
PyObject *arglist, *pFunc;
char imgData[10];
int ret;
for(int i = 0; i < 10; i++)
imgData = 48 + i;
arglist = Py_BuildValue("s#", imgData, 10);
Py_SetProgramName(argv[0]);
Py_Initialize();
PySys_SetArgv(argc, argv);
for (int k = 0; k < 3; k++) // using loop to imitate dynamic
loading/running script
{
pFunc = LoadScript(argv[1], argv[2]);
ret = RunScript(pFunc, arglist);
}
Py_Finalize();
return 0;
}
The first loop is perfectly ok, but on the second loop, script loading
is successful but running will always fail.
Any ideas would be highly apprecicated.
Thanks,
Liping
I am currently involved in a project that needs to load/run a python
script dynamically in a C application. The sample code is as
following:
PyObject *LoadScript(char *file, char *func)
{
PyObject *pName, *pModule, *pDict, *pFunc;
pName = PyString_FromString(file);
pModule = PyImport_Import(pName);
pDict = PyModule_GetDict(pModule);
pFunc = PyDict_GetItemString(pDict, func);
return pFunc;
}
int RunScript(PyObject *pFunc, PyObject *arglist)
{
PyObject *pValue = PyObject_CallFunction(pFunc, "O", arglist);
int ret = PyInt_AsLong(pValue);
return ret;
}
int main(int argc, char *argv[])
{
PyObject *arglist, *pFunc;
char imgData[10];
int ret;
for(int i = 0; i < 10; i++)
imgData = 48 + i;
arglist = Py_BuildValue("s#", imgData, 10);
Py_SetProgramName(argv[0]);
Py_Initialize();
PySys_SetArgv(argc, argv);
for (int k = 0; k < 3; k++) // using loop to imitate dynamic
loading/running script
{
pFunc = LoadScript(argv[1], argv[2]);
ret = RunScript(pFunc, arglist);
}
Py_Finalize();
return 0;
}
The first loop is perfectly ok, but on the second loop, script loading
is successful but running will always fail.
Any ideas would be highly apprecicated.
Thanks,
Liping