python调用c/c++ 编译时报错Py_InitModule‘Py_InitModule’ was not declared in this scope

文章介绍了在Python3中,由于Py_InitModule已淘汰,如何更新C代码以使用PyModule_Create创建模块。通过修改C源码,创建PyModuleDef结构体,然后用PyModule_Create初始化模块,解决编译错误问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1 首先给出错误的程序 great.c

#include <Python.h>

int great_function(int a) {
    return a + 1;
}

static PyObject * _great_function(PyObject *self, PyObject *args)
{
    int _a;
    int res;

    if (!PyArg_ParseTuple(args, "i", &_a))
        return NULL;
    res = great_function(_a);
    return PyLong_FromLong(res);
}

static PyMethodDef GreateModuleMethods[] = {
    {
        "great_function",
        _great_function,
        METH_VARARGS,
        ""
    },
    {NULL, NULL, 0, NULL}
};

PyMODINIT_FUNC initgreat_module(void) {
    (void) Py_InitModule("great_module", GreateModuleMethods);
}

2 编译

Linux终端输入命令:

gcc -fPIC -shared great.c -I/usr/include/python3.10 -o great.so

注意:

编译时,先查看安装python的版本是多少,然后根据python版本号修改编译命令

如安装的python是3.xx.yy,那么编译命令

gcc -fPIC -shared great.c -I/usr/include/python3.xx -o great.so

编译报错

原因

在python3中,Py_InitModule模块已被淘汰

解决

修改great.c文件的部分:创建一个PyModuleDef结构,然后将其引用传递给PyModule_Create。

再次编译并运行

3完整程序

#include <Python.h>

int great_function(int a) {
    return a + 1;
}

static PyObject * _great_function(PyObject *self, PyObject *args)
{
    int _a;
    int res;

    if (!PyArg_ParseTuple(args, "i", &_a))
        return NULL;
    res = great_function(_a);
    return PyLong_FromLong(res);
}

static PyMethodDef GreatMethods[] = {
    {
        "great_function",
        _great_function,
        METH_VARARGS,
        ""
    },
    {NULL, NULL, 0, NULL}
};

static struct PyModuleDef greatModule={
    PyModuleDef_HEAD_INIT,
    "great", /*module名称*/
    "usage: great.great_function(int a)\n", /*模块的功能说明文件,可为NULL*/
    -1,
    GreatMethods
};
    

PyMODINIT_FUNC PyInit_great(void) 
{
    return PyModule_Create(&greatModule);

}   

great.c文件参考:Python与C/C++混合编程 - 知乎 (zhihu.com)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值