简体   繁体   English

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

[英]Segmentation fault (core dumped). Using C module in python

I am newbie in python and I am trying to launch python script with a module writen on C. I am getting Segmentation fault (core dumped) error when I am trying to launch python script. 我是python中的新手,我正在尝试使用C上写的模块启动python脚本。当我尝试启动python脚本时,我收到了Segmentation fault(core dumped)错误。 Here is a C code: 这是一个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);
}

and the python script: 和python脚本:

from input_device import device_open
device_open(1)

Could someone take a look and point me in the right direction, what I am doing wrong. 有人可以看看并指出我正确的方向,我做错了什么。 Thanks in advance. 提前致谢。

Is it legitimate to return NULL without setting an exception, or making sure that one has been set by a function you have called? 在没有设置异常的情况下返回NULL ,或者确保已经调用的函数设置了一个是否合法? I thought that NULL was a signal that Python could go look for an exception to raise for the user. 我认为NULL是一个信号,Python可以寻找为用户引发的异常。

I am not sure that the Py_INCREF(pyfd); 我不确定Py_INCREF(pyfd); is necessary; 有必要的; doesn't the object already have a refcount of 1 upon creation? 对象在创建时是否已经有1的引用数?

Your function receives a tuple of arguments. 你的函数接收一个参数元组。 You need to extract the integer from the tuple: 您需要从元组中提取整数:

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

    if (!PyArg_ParseTuple(args, "i", &nr))
        return NULL;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM