#include <Python.h>
#include <math.h>
static PyObject* interpolate(PyObject* self, PyObject* args) {
const Py_ssize_t tl = 2;
const Py_ssize_t ll = 0;
int nx, ny, angle, distance;
if (!PyArg_ParseTuple(args, "iiii", &nx, &ny, &angle, &distance)) {
return NULL;
}
PyObject* pos_list = PyList_New(ll);
for (int i = 0; i < distance; i++) {
double x = -i * cos(angle * M_PI / 180);
double y = -i * sin(angle * M_PI / 180);
PyObject *pos = PyTuple_Pack(tl, x, y);
PyList_Append(pos_list, pos);
}
return pos_list;
}
当我从Python导入模块时,代码一直在抛出分段错误。为什么会发生这种情况,因为我对C和C扩展真的很陌生。不确定是否正确执行我的setup.py代码。我认为这个错误与我返回的pos_list变量和math.h没有正确包含有关。我删除math.h罪和COS的东西,并切换到Py_BuildValue一个简单的整数
from distutils.core import setup, Extension
module1 = Extension('gameMath',
sources = ['interpolate.c'],
include_dirs = ['/usr/include'],
libraries = ['math'])
setup (name = 'gameMath',
version = '1.0',
description = 'game math',
ext_modules = [module1])
发布于 2018-06-13 13:42:57
假设模块样板是正确的(还没有包括它),并且setup.py实际构建代码是正确的(它不像发布的那样),并且以明显的方式调用它,这里至少有一个可能的分段错误:
PyObject *pos = PyTuple_Pack(tl, x, y);
作为.PyTuple_Pack
文件:
返回大小的新元组对象n,或零在失败的时候。将元组值初始化为后续的nC论点指向Python对象。
不是将指针传递给Python对象,而是将其加倍传递。因此,它将尝试将每一个重复解释为一个指针,这很可能是分段错误1。
要么需要构造两个Pythonfloat
对象PyFloat_FromDouble
,或Py_BuildValue
PyObject *pos = Py_BuildValue("(ff)", x, y);
https://stackoverflow.com/questions/-100005355
复制相似问题