在M上编译python3扩展模块

2024-09-27 20:19:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试用C语言编写Python extension module,我运行的是macOS Catalina,并且有python3的自制安装(带有默认安装设置)。当我试图编译以下文件时:

#include <Python/Python.h>

static PyObject* world(PyObject* self, PyObject* args)
{
    printf("Hello world!\n");
    Py_RETURN_NONE;
}

static PyMethodDef methods[] = {
    {"world", world, METH_VARARGS, "Prints \"Hello world!\""},
    {NULL, NULL, 0, NULL}
};

static struct PyModuleDef module = {
    PyModuleDef_HEAD_INIT,
    "name for the module",
    "docstring for the module",
    -1,
    methods
};

PyMODINIT_FUNC PyInit_hello(void)
{
    return PyModule_Create(&module);
}

通过在终端中运行gcc hello.c,我得到以下消息:

hello.c:15:5: error: use of undeclared identifier
      'PyModuleDef_HEAD_INIT'
    PyModuleDef_HEAD_INIT,
    ^
hello.c:14:27: error: variable has incomplete type
      'struct PyModuleDef'
static struct PyModuleDef module = {
                          ^
hello.c:14:15: note: forward declaration of 'struct PyModuleDef'
static struct PyModuleDef module = {
              ^
hello.c:24:12: warning: implicit declaration of function
      'PyModule_Create' is invalid in C99
      [-Wimplicit-function-declaration]
    return PyModule_Create(&module);
           ^
1 warning and 2 errors generated.

有办法解决这个问题吗?我尝试过使用-L-I标志,但没有效果。我认为这可能是因为它使用的是python2而不是python3的头。你知道吗


Tags: ofhelloworldinitcreatestaticnullhead
1条回答
网友
1楼 · 发布于 2024-09-27 20:19:12

使用distutils

创建设置.py. e、 g

from distutils.core import setup, Extension

def main():
    setup(name="hello",
            version="1.0.0",
            description="desc",
            author="<your name>",
            author_email="a@b.com",
            ext_modules=[Extension("hello",["hello.c"])])

if __name__ == "__main__":
    main()

在c中,文件更改包括:

#include <Python.h>

假设你的c文件名是hello.c设置.py位于同一目录中:

python3 setup.py install

在您的例子中,验证它是“python3”还是“python”。 这将构建并安装您的模块,您应该能够看到编译器和链接器命令

相关问题 更多 >

    热门问题