[Numpy-discussion] problems with compiling and loading C++ extension

Fernando Perez fperez at colorado.edu
Wed Apr 7 21:26:10 CDT 2004


Faheem Mitha wrote:
> Dear People,
> 
> I have been having an odd problem with compiling and loading a simple
> C++ extension to python (as a .so file in Linux). Unfortunately, I'll
> need to include my files in here so I apologize in advance for the
> length of this message.

Are you sure you have all the needed 'extern C' declarations in place? 
Remember, you'll be compiling this thing with a C++ compiler, but it will be 
called by Python's C runtime.  Hence, _all_ python-visible functions will need 
to be wrapped in extern C calls, including your module initializer (you often 
don't think of this one, because it's implicitly

Here's a typical snippet for a python-visible function in one of my C++ 
blitz-based extensions:

// mts_contract
extern "C" {
     static PyObject* mts_contract(PyObject *self, PyObject *args)
     {

         PyArrayObject *M_array, *T_array;
...

and here's what the module initializer looks like:


/* Module initializer -- called on first import.
    It *must* be called initMODULENAME */
extern "C" void initutils_()
{
     import_array();

     // Initialize the dimension dispatch tables
     init_mts_contract_funcs();
     init_mtt_contract2_funcs();
     init_mseqtt_contract2_funcs();

     // Create the module and add the functions
     PyObject* mod = Py_InitModule4("utils_",
                                    compiled_methods,
                                    module_doc,
                                    (PyObject*)NULL,
                                    PYTHON_API_VERSION);

     // Add some symbolic constants to the module
     PyObject* mod_dict = PyModule_GetDict(mod);

     // Make a module-level exception
     // The first argument is what the exception class will appear to be
     // in python. The return value is a class object.
     utils_Error = PyErr_NewException("utils_.utils_Error",
                                      NULL, NULL);

     // Add it to the module's dictionary. Second argument is the key
     PyDict_SetItemString(mod_dict, "utils_Error", utils_Error);

     // Add other constants here
     PyDict_SetItemString(mod_dict, "__all__",
                          Py_BuildValue("sss",
                                        "mts_contract2",
                                        "mtt_contract2",
                                        "mseqtt_contract2"
                                        ));

     // Check for errors
     if (PyErr_Occurred())
         Py_FatalError("can't initialize module utils_");
}


I hope this helps you.  Mail me if you want the full files (this is old code I 
don't use anymore, so it may not quite compile now anymore, but you can still 
look a it).

Cheers,

f





More information about the Numpy-discussion mailing list