Python的C扩展无法正常工作

问题描述 投票:4回答:1

C扩展安装正常(没有警告和错误),但当我尝试导入它时,我收到以下错误:

ValueError中的文件“”,第1行:模块函数无法设置METH_CLASS或METH_STATIC

这是代码,可能是什么问题/我可以做些什么来修复并避免这个错误?非常感谢你提前。编辑:由于某种原因,编译器没有向我显示所有警告。我修复了警告并更新了代码,但我仍然得到同样的错误

#include<math.h>
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#include<Python.h>


PyObject *makelist(unsigned int array[], size_t size) {
    PyObject *l = PyList_New(size);
    for (size_t i = 0; i != size; ++i) {
        PyList_SET_ITEM(l, i, Py_BuildValue("i", array[i]));
    }
    return l;
}

static PyObject *module_func(PyObject *self, PyObject *args) {
    unsigned int n;

    if (!PyArg_ParseTuple(args, "i", &n)) {
        return NULL;
    }

    const unsigned int size = n >> 3 + (n & 15 ? 1 : 0);
    const unsigned int arraySize = n >> 1;

    char* bitArray = (char*)malloc(size);

    for (unsigned int i = 0; i < size; i++) {
        *(bitArray + i) = 0b11111111;
    }

    int num;
    for (unsigned int i = 1; i <= ((unsigned int)sqrt(n)) >> 1; i++) {
        int ni = i - 1;
        if ((*(bitArray + (ni >> 3)) >> (ni & 7)) & 1) {
            num = (i << 1) | 1;
            for (unsigned int j = num * num; j <= n; j += num << 1) {
                *(bitArray + ((j - 3) >> 4)) &= ~(1 << (((j - 3) >> 1) & 7));
                // *(bitArray + ((((j - 1) >> 1) - 1) >> 3)) &= ~(1 << (((((j - 1) >> 1) - 1) >> 3) & 7));
            }
        }
    }

    unsigned int* primes = (unsigned int*)malloc((arraySize * sizeof(int)));
    *primes = 2;
    int counter = 1;
    for (unsigned int index = 1; index < arraySize; index++) {
        if ((*(bitArray + ((index - 1) >> 3)) >> ((index - 1) & 7)) & 1) {
            *(primes + counter) = (index << 1) | 1;
            counter++;
        }
    }
    *(primes + counter) = 0;
    return Py_BuildValue("O", makelist(primes, sizeof(primes)));
}

static PyMethodDef module_methods[] = {
    { "func", (PyCFunction)module_func, METH_VARARGS, NULL }
};

static struct PyModuleDef func =
{
    PyModuleDef_HEAD_INIT,
    "module",
    "Null",
    -1,
    module_methods
};

PyMODINIT_FUNC PyInit_func(void) {
    return PyModule_Create(&func);
}
python c python-3.x module
1个回答
3
投票

你忘记了null终止你的module_methods

static PyMethodDef module_methods[] = {
    { "func", (PyCFunction)module_func, METH_VARARGS, NULL },
    {NULL}
};

Python查找空条目以确定PyMethodDef数组的结尾。如果没有null终结符,Python就不知道数组的结束位置,并且它会从数组的末尾开始寻找更多方法。

© www.soinside.com 2019 - 2024. All rights reserved.