Python C扩展缺少功能

ned*_*004 5 python python-extensions

在遵循针对Python的C扩展教程时,我的模块似乎缺少其内容。虽然构建和导入模块没有问题,但是在模块中使用该功能失败。我在macOS上使用Python 3.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);
}
Run Code Online (Sandbox Code Playgroud)

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])
Run Code Online (Sandbox Code Playgroud)

测试和错误是

>>> import test
>>> test.add(4, 5)
AttributeError: module 'test' has no attribute 'add'
Run Code Online (Sandbox Code Playgroud)

DYZ*_*DYZ 2

看起来您导入了标准模块test(检查test.__path__)。如果是这样,请重命名您的模块。