python - 构建 Numpy C++ 扩展;调用 PyArray_FROM_OTF 时出现段错误

标签 python c++ numpy segmentation-fault

我正在学习如何构建 Numpy 扩展。我正在遵循的教程是这个:

https://gist.github.com/kanhua/8f1eb7c67f5a031633121b6b187b8dc9

我的代码如下所示:

module.cpp

#include "/usr/local/Cellar/python/3.7.7/Frameworks/Python.framework/Versions/3.7/include/python3.7m/Python.h"

#include "numpy/ndarraytypes.h"
#include "numpy/ufuncobject.h"
#include "numpy/npy_3kcompat.h"

#include <iostream>

PyObject* get_dimension(PyObject *dummy, PyObject* args) {
    PyObject *arg1=NULL;
    PyObject *arr1=NULL;
    int nd = 1;

    if (!PyArg_ParseTuple(args, "O", &arg1))
        return NULL;

    // THIS LINE PRINTS A VALID ADDRESS
    std::cout << arg1 << std::endl;

    //=====================
    // PROBLEM AT THIS LINE
    //=====================
    arr1 = PyArray_FROM_OTF(arg1, NPY_DOUBLE, NPY_ARRAY_IN_ARRAY);

    return PyInt_FromLong(nd);
}

static PyMethodDef matrixsolvers_methods[] = {
    // The first property is the name exposed to Python, fast_tanh, the second is the C++
    // function name that contains the implementation.
    { "get_dimension", (PyCFunction) get_dimension, METH_VARARGS, nullptr },

    // Terminate the array with an object containing nulls.
    { nullptr, nullptr, 0, nullptr }
};

static PyModuleDef matrixsolvers_module = {
    PyModuleDef_HEAD_INIT,
    "matrixsolvers",                        // Module name to use with Python import statements
    "Provides some functions, but faster",  // Module description
    0,
    matrixsolvers_methods                   // Structure that defines the methods of the module
};

PyMODINIT_FUNC PyInit_matrixsolvers() {
    return PyModule_Create(&matrixsolvers_module);
}

setup.py

from distutils.core import setup, Extension
from numpy import get_include

ms_module = Extension('matrixsolvers', sources=['module.cpp'], include_dirs=[get_include()])

setup(name='matrixsolvers', version='1.0',
      description='Python Package that implements matrix solvers in C++',
      ext_modules=[ms_module]
      )

main.py

from matrixsolvers import get_dimension
import numpy as np

get_dimension(np.array([1,2,3]))

要运行我的代码,我在终端中运行以下命令:

pip3 install . 
python3 main.py

现在这一切似乎工作正常,但由于调用 PyArray_FROM_OTF 的行,我遇到了段错误。

谁能解释一下我做错了什么吗?

非常感谢任何指导。

最佳答案

添加import_array();之前return PyModule_Create(&matrixsolvers_module);

参见https://numpy.org/devdocs/user/c-info.how-to-extend.html了解详情。

关于python - 构建 Numpy C++ 扩展;调用 PyArray_FROM_OTF 时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60748039/

相关文章:

python - 如何在Python中返回多维数组的子数组?

python - 计算文件每一行的每个单词的字符数

python - 无法在 Python 中显示 TreeView

python - 从 Tkinter 内的 For 循环返回不同的标签 (python)

c++ - 编译器不能在 Vector_const_iterator 和 Vector_iterator 之间使用 "convert",即使两者的方法都可用

c++ - 为什么装饰模式适用于指针而不适用于引用?

python - 如何使用 `np.fromfile` 从二进制文件中读取连续数组?

python - 在方法中使用断言 - Python

c++ - 如何释放静态区域中的内置数据 token

python - 在 Python 中求解 ODE 时,如何获得比 linspace 更多的变量值? (编辑)