gpt4 book ai didi

Python C 扩展缺少函数

转载 作者:太空狗 更新时间:2023-10-30 01:24:38 25 4
gpt4 key购买 nike

在学习 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);
}

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__)。如果是这样,请重命名您的模块。

关于Python C 扩展缺少函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56453466/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com