【问题标题】:segmentation fault python main.py分段错误 python main.py
【发布时间】:2021-08-15 04:39:36
【问题描述】:

我写了一个 c++ 模块,女巫应该被导入 Python。下面是代码,C++ 部分和 Python 部分。 C++ 函数method_sum 应该将值的双精度值返回给 python。

模块.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'])])

【问题讨论】:

  • 请提供预期的minimal, reproducible example (MRE)。我们应该能够复制和粘贴您的代码的连续块,执行该文件,并重现您的问题以及跟踪问题点的输出。这让我们可以根据您的测试数据和所需的输出来测试我们的建议。这包括引发错误的驱动程序、跟踪数据和完整的错误消息。

标签: python c++ python-c-api


【解决方案1】:

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

以下方法也有效,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);
}

【讨论】:

  • OP 试图将int 解析为const int*,很可能是由于错误地修改了无处不在的spam.system("ls -la") 示例参数,该参数是const char*(C 字符串)。但是,如果他们确实想传递int *,则应使用"O" 而不是"i",将其解析为任意对象。
猜你喜欢
  • 2013-10-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多