Extending Python 3 with C++

Extending Python 3 with C++

本文关键字:C++ with Python Extending      更新时间:2023-10-16

我正在尝试使用这里给出的指令扩展Python 3,我很有信心到目前为止我已经正确地遵循了指令,但它要求我包含以下代码:

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;
}

我在MSVC++2010上写这篇文章,它警告我&spammodule是未定义的(模块的名称是spammodule.cpp),但它在指令中没有定义它,所以我认为它应该自动将其识别为模块的名称。

完整代码为:

#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;
}

您仍在编写C++,因此仍需要在某处声明spammodule。稍后在同一页上给出:

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
};

No No No,PyModule_Create()接受指向模块定义结构的指针,与源文件的名称完全无关。