More details on the init function

From DANSE

When it first loads the extension library, the interpretter needs to know how to find its way around. That's what the init function does. The name of the function has to be initfilename, where filename is the name of the library with no extension. So on Windows, if the actual library file will be called _numbers.dll, then the init function will look like:

extern "C" 
__declspec(dllexport) 
void init_numbers(void)
{
    PyObject *m = 
        Py_InitModule4(
            "_numbers",   // name of the module
            numbersMethods,  // name of the method table
            "C++ Numbers class", // doc string for module
            0,   // last two never change
            PYTHON_API_VERSION);
    return;
}

The important thing here is to call a function from the Py_InitModule family. This version calls one of the more complex members; it gives a chance to do some advanced processing. I show it here because this is what the "package" shell script uses. In fact, if you use the packag template, you'll hardly ever have to touch this code.

The __declspec(dllexport) is Windows-specific. On linux, this would look like

extern "C"
void init_numbers(void)
{
...
}

The advanced Python user may want to have some other code execute here, but for starters, this is all you need.

The platform independent way to combine these uses the C preprocessor:

extern "C"
#ifdef WIN32
__declspec(dllexport)
#endif
void init_numbers(void)
{
...
}

Note that the declspec bit must go after the extern "C" declaration.

Personal tools
Document Uploads/Links