1

I'm trying to extend Python 3 using instructions given here and I'm fairly confident I've followed the instructions correctly so far, but it asks me to include this code:

PyMODINIT_FUNC
PyInit_spam(void)
{
    PyObject *m;

    m = PyModule_Create(&spammodule);
    if (m == NULL)
        return NULL;

    SpamError = PyErr_NewException("spam.error", NULL, NULL);
    Py_INCREF(SpamError);
    PyModule_AddObject(m, "error", SpamError);
    return m;
}

I'm writing this in MSVC++ 2010 and it's warning me that &spammodule is undefined (the name of the module is spammodule.cpp), but it doesn't define it anywhere in the instructions so I assume that it should recognise it automatically as the name of the module.

The full code is:

#include <Python.h>
#include <iostream>
using namespace std;

static PyObject *SpamError;

int main()
{
    cout << "Test" << endl;
    system("PAUSE");
    return(0);
}

static PyObject *spam_system(PyObject *self, PyObject *args)
{
    const char *command;
    int sts;

    if (!PyArg_ParseTuple(args, "s", &command))
        return NULL;
    sts = system(command);
    return PyLong_FromLong(sts);
}

PyMODINIT_FUNC
PyInit_spam(void)
{
    PyObject *m;

    m = PyModule_Create(&spammodule);
    if (m == NULL)
        return NULL;

    SpamError = PyErr_NewException("spam.error", NULL, NULL);
    Py_INCREF(SpamError);
    PyModule_AddObject(m, "error", SpamError);
    return m;
}
3
  • There are no such things as modules in C++. You'll probably want to start over and read a good C++ book before continuing, you'll save yourself a lot of frustration. Commented Feb 24, 2012 at 23:41
  • 1
    @SethCarnegie, he's using the Python C API, so The C Programming Language (2nd ed.) should be sufficient. Commented Feb 24, 2012 at 23:43
  • I'll be studying C++ next term at university, though I'm under time constraints to finish a project in Python at the moment, so I don't have much time to learn C++, but thanks. Commented Feb 24, 2012 at 23:54

2 Answers 2

2

You're still writing C++, so you still need to declare spammodule somewhere. This is given later on the same page:

static struct PyModuleDef spammodule = {
   PyModuleDef_HEAD_INIT,
   "spam",   /* name of module */
   spam_doc, /* module documentation, may be NULL */
   -1,       /* size of per-interpreter state of the module,
                or -1 if the module keeps state in global variables. */
   SpamMethods
};
Sign up to request clarification or add additional context in comments.

Comments

1

No no no, PyModule_Create() accepts a pointer to the module definition structure and has absolutely nothing to do with the name of the source file.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.