1

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.

2 Answers 2

3

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?

Sign up to request clarification or add additional context in comments.

1 Comment

I don't think returning NULL is valid. You will either need to raise an exception or return Py_None (don't forget to Py_INCREF(Py_None) !).
0

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.