【问题标题】:Segmentation fault (core dumped). Using C module in python分段错误(核心转储)。在python中使用C模块
【发布时间】:2013-04-05 11:25:18
【问题描述】:

我是 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)

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

【问题讨论】:

    标签: python c python-2.7


    【解决方案1】:

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

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

    【讨论】:

    • 我不认为返回 NULL 是有效的。您将需要引发异常或返回 Py_None(不要忘记 Py_INCREF(Py_None) !)。
    【解决方案2】:

    你的函数接收一个参数元组。您需要从元组中提取整数:

    static PyObject* input_device_open(PyObject* self, PyObject* args)
    {
        int fd, nr;
        PyObject* pyfd;
    
        if (!PyArg_ParseTuple(args, "i", &nr))
            return NULL;
    

    【讨论】:

      猜你喜欢
      • 2015-02-27
      • 1970-01-01
      • 2022-01-14
      • 2017-02-25
      • 2016-07-12
      • 2018-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多