简体   繁体   English

分段错误 python main.py

[英]segmentation fault python main.py

I wrote a c++ module witch should be imported into Python.我写了一个 c++ 模块,应该将其导入 Python。 Below are both Codes, the C++ part and the Python part.下面是两个代码,C++ 部分和 Python 部分。 The C++ function method_sum should return the double of a value to python. C++ function method_sum应该将值的双精度值返回给 python。

module.cpp:模块.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:主要.py:

import module

print(module.sum(18))

setup.py:设置.py:

from distutils.core import setup, Extension

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

I changed method_sum to the following and main.py prints 36 instead of segfaulting.我将method_sum更改为以下内容,并且main.py打印 36 而不是 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.以下也适用,并且prop仍然是问题中代码中的指针。

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);
}

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

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