python-c API. Following code shows calling python function "add1" from python module "def1"
Expand|Select|Wrap|Line Numbers
- int add(int x, int y)
- {
- double answer;
- Py_Initialize();
- PyObject *modname, *mod, *mdict, *func, *arg1, *arg2, *args, *rslt;
- printf("############INSIDE ADD############\n");
- modname = PyString_FromString("def1");
- if (modname == NULL)
- {
- Py_Exit(0);
- return 0;
- }
- mod = PyImport_Import(modname);
- if (mod == NULL)
- {
- Py_Exit(0);
- return 0;
- }
- if (mod)
- {
- mdict = PyModule_GetDict(mod);
- func = PyDict_GetItemString(mdict, "add1");
- if (func)
- {
- if (PyCallable_Check(func))
- {
- arg1 = PyLong_FromLong((double)x);
- arg2 = PyLong_FromLong((double)y);
- printf("############ARGS FORMED############\n");
- args = PyTuple_New(2);
- PyTuple_SetItem(args, 0, arg1);
- PyTuple_SetItem(args, 1, arg2);
- printf("############CALLING############\n");
- rslt = PyObject_CallObject(func, args);
- if (rslt)
- {
- answer = PyLong_AsLong(rslt);
- Py_XDECREF(rslt);
- }
- Py_XDECREF(arg1);
- Py_XDECREF(arg2);
- Py_XDECREF(args);
- }
- }
- Py_XDECREF(mod);
- }
- Py_XDECREF(modname);
- // Py_Finalize();
- // printf("############%d",answer);
- return (int)answer;
- }
the problem is i should know the module name and function name in order to call.
Is it possible to get these two things at run time.
Basically i want to implement pointer to function, so i dont know the file name and function name at compile and link time.
And also Py_Finalize returns exception thats why i commented it