Tillmann
Tillmann

Reputation: 61

segmentation fault python main.py

I wrote a c++ module witch should be imported into Python. Below are both Codes, the C++ part and the Python part. The C++ function method_sum should return the double of a value to python.

module.cpp:

#define PY_SSIZE_T_CLEAN
#include <Python.h>

static PyObject *method_sum(PyObject *self, PyObject *args) {
  const int *prop;

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

  int result = *prop + *prop;
  return Py_BuildValue("i", result);
}

static PyMethodDef ModuleMethods[] = {
    {"sum", method_sum, METH_VARARGS, "description of the function"},
    {NULL, NULL, 0, NULL}
};

static struct PyModuleDef module = {
    PyModuleDef_HEAD_INIT,
    "module",
    "description of the module",
    -1,
    ModuleMethods
};

PyMODINIT_FUNC PyInit_module(void) {
    return PyModule_Create(&module);
}

main.py:

import module

print(module.sum(18))

setup.py:

from distutils.core import setup, Extension

setup(name='module', version='1.0', ext_modules=[Extension('module', ['module.cpp'])])

Upvotes: 0

Views: 310

Answers (1)

Nathan Mills
Nathan Mills

Reputation: 2279

I changed method_sum to the following and main.py prints 36 instead of segfaulting.

static PyObject *method_sum(PyObject *self, PyObject *args) {
  int prop;

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

  int result = prop + prop;
  return Py_BuildValue("i", result);
}

The following also works and prop is still a pointer like in the code in the question.

static PyObject *method_sum(PyObject *self, PyObject *args) {
  const int *prop = new int;

  if (!PyArg_ParseTuple(args, "i", prop)) {
    delete prop;
    return NULL;
  }

  int result = *prop + *prop;
  delete prop;
  return Py_BuildValue("i", result);
}

Upvotes: 2

Related Questions