【PYTHON】Python C擴充套件缺少功能

2020-12-02 PYTHON

在學習c擴充套件python教程時,我的模組似乎缺少它的內容。在構建和匯入模組時沒有問題,但是在模組中使用函式失敗。我在MacOS上使用Python3.7。
testmodule.c

#define PY_SSIZE_T_CLEAN
#include <Python.h>

static PyObject* add(PyObject *self, PyObject *args) {
    const long long x, y;
    if (!PyArg_ParseTuple(args, "LL", &x, &y)) {
        return NULL;
    }
    return PyLong_FromLongLong(x + y);
}

static PyMethodDef TestMethods[] = {
    {"add", add, METH_VARARGS, "Add two numbers."},
    {NULL, NULL, 0, NULL}
};

static struct PyModuleDef testmodule = {
    PyModuleDef_HEAD_INIT,
    "test",
    NULL,
    -1,
    TestMethods
};

PyMODINIT_FUNC PyInit_test(void)
{
    return PyModule_Create(&testmodule);
}

setup.py
from distutils.core import setup, Extension

module1 = Extension('test', sources=['testmodule.c'])

setup(name='Test',
      version='1.0',
      description='Test package',
      ext_modules=[module1])

測試和錯誤是
>>> import test
>>> test.add(4, 5)
AttributeError: module 'test' has no attribute 'add'

解決辦法

看起來您匯入了標準模組test(選中test.__path__)。如果是,請重新命名模組。

出處

Have any Question?

Let us answer it!