python - 段错误(核心已转储)。在 python 中使用 C 模块

标签 python c python-2.7

我是 python 的新手,我正在尝试使用在 C 上编写的模块启动 python 脚本。当我尝试启动 python 脚本时出现段错误(核心转储)错误。 这是一个 C 代码:

// input_device.c  
#include "Python.h"

#include "input.h"

static PyObject* input_device_open(PyObject* self, PyObject* id)
{
    int fd, nr;
    PyObject* pyfd;

    if (!PyInt_Check(id))
        return NULL;

    nr = (int)PyInt_AsLong(id);
    fd = device_open(nr, 0);
    if (fd == -1)
        return NULL;
    pyfd = PyInt_FromLong(fd);
    Py_INCREF(pyfd);
    return pyfd;
}

static PyMethodDef module_methods[] =
{
    { "device_open", (PyCFunction)input_device_open, METH_VARARGS, "..." },
    { NULL, NULL, 0, NULL }
};

PyMODINIT_FUNC initinput_device(void)
{
    Py_InitModule4("input_device", module_methods, "wrapper methods", 0, PYTHON_API_VERSION);
}

和 python 脚本:

from input_device import device_open
device_open(1)

有人可以看看并指出正确的方向,我做错了什么。提前致谢。

最佳答案

返回 NULL 而不设置异常,或者确保异常已被您调用的函数设置是否合法?我认为 NULL 是一个信号,表明 Python 可以去寻找为用户引发的异常。

我不确定 Py_INCREF(pyfd); 是否必要;对象在创建时是否已经有 1 的引用计数?

关于python - 段错误(核心已转储)。在 python 中使用 C 模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15832700/

相关文章:

c - NDK-C 文件中 .a 文件的使用

c - Oracle Pro*C : Handling end of fetch cursor

将列表转换为类字段的Pythonic方法

python - 如何使用 python27 应用程序引擎 webapp2 框架组织文件

python - 正则表达式查找嵌套括号之间的文本

python - 将 XML 数据解析为 pandas 多索引数据帧

python - 如何将列旋转到标题? - python Pandas 数据框

Python UTF-8 Latin-1 显示错误字符

c - 如何在 C 中比较两个不区分大小写的字符?

python-2.7 - 如何使用 “cv2.createTrackbar()”函数调整流视频帧的大小?