C++ calling a Python extension module

Jeremy Black jblack at one.net
Mon Dec 6 17:28:26 EST 1999


Is there a limitation or bug in the NT version of Python that disallows
importing python extension modules from C++?

I am having difficulty importing a python module from C++ that imports a
python extension module written in C.  The code (listed below) fails on the
very last line where it calls PyImport_ImportModule and returns NULL.  Note
that PyImport_ImportModule ONLY fails if the module that I am attempting to
import is dependent on an extension module written in C.  i.e. If I take my
JPBFile.py module and remove the statement that imports the extension
module, PyImport_ImportModule works fine.  In my case my extension module is
a pyd file.  The extension module has been tested and works fine if used
from a Python script.

As a test, I changed the last line to import "Tkinter" which (you guessed
it) also fails since it is dependent on the _tkinter.pyd file.

I am running all these tests on Windows NT using VC++ v5.0.  The python
interpreter installed is v1.5.2.

Here is the code that I am using:

// Initialize python if necessary
   if (!Py_IsInitialized())
      Py_Initialize();

   // Import the python module
   PyObject* filemodule;

   const char* homeDir = getenv ("JPB_HOME");
   if (homeDir)
   {
   // Just in case the JPB_HOME is not already in the python module source
   // path, add it and then import the module.
      PyRun_SimpleString("import sys");
      char buffer[200];
      sprintf(buffer, "sys.path.append('%s')", homeDir);
      PyRun_SimpleString(buffer);
      filemodule = PyImport_ImportModule ("JPBFile");


Thanks!
   Jeremy Black
   jblack at one.net






More information about the Python-list mailing list