【问题标题】:Extending Python, numpy with C — is code OK?用 C 扩展 Python,numpy —— 代码可以吗?
【发布时间】:2014-08-07 21:12:47
【问题描述】:

这是我第一次尝试扩展 Python 函数。 在 Python 中,我有 4 维浮点数列表:

import polarMM    
data = [[[(102.0, 815.0), (84.0, 791.0), (302.0, 806.0), (38.0, 801.0)], [(70.0, 696.0), (52.0, 653.0), (172.0, 649.0), (13.0, 647.0)], [(77.0, 696.0), (143.0, 653.0), (211.0, 649.0), (197.0, 647.0)], [(115.0, 815.0), (228.0, 791.0), (371.0, 806.0), (322.0, 801.0)]], [[(167.0, 815.0), (242.0, 791.0), (465.0, 806.0), (339.0, 801.0)], [(135.0, 696.0), (186.0, 653.0), (329.0, 649.0), (271.0, 647.0)], [(142.0, 696.0), (277.0, 653.0), (373.0, 649.0), (489.0, 647.0)], [(180.0, 815.0), (397.0, 791.0), (533.0, 806.0), (623.0, 801.0)]]]  
print polarMM.test(data)

这是我的代码;在我用一行来解析列表之前它就起作用了。 不知道:是我的环境不好还是这部分代码有问题?

static PyObject *
polarMM_test(PyObject *self, PyObject *args)
    {
    PyObject *objContours;
    PyArrayObject *pyContours;

    if (!PyArg_ParseTuple(args, "OO", &objContours, &objMMValues))
            return NULL;   

     // **** AND HERE CODE CRASHES *****:
    pyContours = (PyArrayObject*) PyArray_FROMANY (objContours, PyArray_DOUBLE, 0, 4, NPY_IN_ARRAY);

    return Py_BuildValue("s", "just test");
}

崩溃的堆栈跟踪:

Exception Type:  EXC_BAD_ACCESS (SIGSEGV)
Exception Codes: KERN_INVALID_ADDRESS at 0x0000000000000228
...
Thread 0 Crashed:: Dispatch queue: com.apple.main-thread
0   polarMM.so                      0x00000001002f1d1d polarMM_test + 45 (polarMM.c:63)
1   org.python.python               0x00000001000c2fad PyEval_EvalFrameEx + 21405
2   org.python.python               0x00000001000c4fb3 PyEval_EvalCodeEx + 2115
3   org.python.python               0x00000001000c50d6 PyEval_EvalCode + 54
4   org.python.python               0x00000001000e995e PyRun_FileExFlags + 174
5   org.python.python               0x00000001000e9bfa PyRun_SimpleFileExFlags + 458
6   org.python.python               0x0000000100100c0d Py_Main + 3101
7   org.python.python               0x0000000100000f14 0x100000000 + 3860

我正在使用 Mac OSX 10.9.3,而不是默认设置 Python 2.7,最新的 numpy。

【问题讨论】:

  • 看起来您尝试取消引用 NULL 指针。 (抱歉,我不知道 C API 的更具体细节。)
  • 你记得在扩展模块的初始化函数中调用import_array()docs.scipy.org/doc/numpy/reference/…)吗?例如,请参阅docs.scipy.org/doc/numpy/user/…
  • 沃伦,你无法想象我现在的感受——经过 20 个小时的头撞。你有权利。谢谢!

标签: python c macos numpy


【解决方案1】:

Warren 说得对:我忘记在模块的初始化函数中调用 import_array()。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-03-29
    • 2023-03-14
    • 2010-09-27
    • 1970-01-01
    • 2023-03-10
    • 1970-01-01
    • 2022-08-18
    相关资源
    最近更新 更多