/Python/importdl.c

http://unladen-swallow.googlecode.com/ · C · 78 lines · 58 code · 13 blank · 7 comment · 15 complexity · 5ba2be4c77f8e18101955e85eb4891be MD5 · raw file

  1. /* Support for dynamic loading of extension modules */
  2. #include "Python.h"
  3. /* ./configure sets HAVE_DYNAMIC_LOADING if dynamic loading of modules is
  4. supported on this platform. configure will then compile and link in one
  5. of the dynload_*.c files, as appropriate. We will call a function in
  6. those modules to get a function pointer to the module's init function.
  7. */
  8. #ifdef HAVE_DYNAMIC_LOADING
  9. #include "importdl.h"
  10. extern dl_funcptr _PyImport_GetDynLoadFunc(const char *name,
  11. const char *shortname,
  12. const char *pathname, FILE *fp);
  13. PyObject *
  14. _PyImport_LoadDynamicModule(char *name, char *pathname, FILE *fp)
  15. {
  16. PyObject *m;
  17. char *lastdot, *shortname, *packagecontext, *oldcontext;
  18. dl_funcptr p;
  19. if ((m = _PyImport_FindExtension(name, pathname)) != NULL) {
  20. Py_INCREF(m);
  21. return m;
  22. }
  23. lastdot = strrchr(name, '.');
  24. if (lastdot == NULL) {
  25. packagecontext = NULL;
  26. shortname = name;
  27. }
  28. else {
  29. packagecontext = name;
  30. shortname = lastdot+1;
  31. }
  32. p = _PyImport_GetDynLoadFunc(name, shortname, pathname, fp);
  33. if (PyErr_Occurred())
  34. return NULL;
  35. if (p == NULL) {
  36. PyErr_Format(PyExc_ImportError,
  37. "dynamic module does not define init function (init%.200s)",
  38. shortname);
  39. return NULL;
  40. }
  41. oldcontext = _Py_PackageContext;
  42. _Py_PackageContext = packagecontext;
  43. (*p)();
  44. _Py_PackageContext = oldcontext;
  45. if (PyErr_Occurred())
  46. return NULL;
  47. m = PyDict_GetItemString(PyImport_GetModuleDict(), name);
  48. if (m == NULL) {
  49. PyErr_SetString(PyExc_SystemError,
  50. "dynamic module not initialized properly");
  51. return NULL;
  52. }
  53. /* Remember the filename as the __file__ attribute */
  54. if (PyModule_AddStringConstant(m, "__file__", pathname) < 0)
  55. PyErr_Clear(); /* Not important enough to report */
  56. if (_PyImport_FixupExtension(name, pathname) == NULL)
  57. return NULL;
  58. if (Py_VerboseFlag)
  59. PySys_WriteStderr(
  60. "import %s # dynamically loaded from %s\n",
  61. name, pathname);
  62. Py_INCREF(m);
  63. return m;
  64. }
  65. #endif /* HAVE_DYNAMIC_LOADING */