0

I tried to write a module for python using the c-api but the module wouldn't import. The problem persists for this minimal example:

#include <Python.h>
#include <stdio.h>

static PyMethodDef CAPMethods[] = {
    {NULL, NULL, 0, NULL}        /* Sentinel for end of array*/
};

static struct PyModuleDef CAPModule = {
   PyModuleDef_HEAD_INIT,
   "puzzler",   /* name of module */
   NULL, /* module documentation, may be NULL */
   -1,       /* -1 if the module keeps state in global variables. */
   CAPMethods, /* Method table */
};

PyMODINIT_FUNC
PyInit_puzzler(void)
{
    printf("Initializing...\n");
    PyObject* module = PyModule_Create(&CAPModule);
    if(module == NULL)
    {
        printf("Minimal Failed!\n");
        Py_RETURN_NONE;
    }
    printf("Success!\n");

    return module;
}

It feels like I'm missing something really obvious but I can't tell what it is. For completeness here is my setup.py:

from distutils.core import setup, Extension

CAP = Extension(
        'puzzler',
        sources = ['minimal.c'],
    )

setup(  name = 'PuzzleSolver',
        version = '1.0',
        description = 'This is a demo package',
        ext_modules = [CAP])

If someone knows what I could do wrong or wants additional information about my setup, feel free to ask in the comments. I compile using python setup.py install (Python 3.3.3 (v3.3.3:c3896275c0f6, Nov 18 2013, 21:19:30) [MSC v.1600 64 bit (AMD64)] on win32).

Here is the python console output when I try it out:

>>> import puzzler
Initializing...
Minimal Failed!
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
SystemError: initialization of puzzler raised unreported exception
WorldSEnder
  • 4,875
  • 2
  • 28
  • 64
  • 2
    I can't reproduce this error on Linux. I'm running `Python 3.4.3 (default, Mar 25 2015, 17:13:50) [GCC 4.9.2 20150304 (prerelease)] on linux`. One potential bug is in your `if(module == NULL) { ...; Py_RETURN_NONE; }`. If `module` is `NULL`, an exception has been raised, and you should return `NULL` instead of `Py_RETURN_NONE` to indicate to the calling method your module initialization function failed. – Uyghur Lives Matter Jun 04 '15 at 13:24
  • Replaced with `return NULL;` and now it says `Memory Error`, any ideas? Btw, I "fixed" it by replacing the -1 with a zero in `CAPModule ` – WorldSEnder Jun 04 '15 at 15:35
  • `0` is a reasonable value, but I don't know why that fixes your issue. The documentation for [PyModuleDef.m_size](https://docs.python.org/3/c-api/module.html#c.PyModuleDef.m_size) indicates a size of `-1` "means that the module can not be re-initialized because it has global state" but as far as I can tell your module shouldn't be reinitialized. – Uyghur Lives Matter Jun 04 '15 at 22:56

0 Answers0