简体   繁体   中英

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. Here is a C code:

// 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:

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? I thought that NULL was a signal that Python could go look for an exception to raise for the user.

I am not sure that the Py_INCREF(pyfd); is necessary; doesn't the object already have a refcount of 1 upon creation?

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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