首页 > 解决方案 > 运行 PyArray_Max 命令时程序崩溃

问题描述

我正在尝试将一个 numpy 数组传递给一些 C++ 增强代码。运行 PyArray_Max 命令时,我的 boost 代码崩溃而没有任何错误输出。知道为什么会这样吗?

我使用命令“python numpy_setup.py build_ext --inplace”来构建我的程序。所有文件应位于同一目录中。

根据 github 上的此 API 代码第 337 行,我正确使用了 PyArray_Max 命令: https ://github.com/davidandrzej/pSSLDA/blob/master/FastLDA.c

互联网上没有任何其他代码示例(除了链接的 API 文件)显示如何使用 PyArray_Max。

如果您运行我的代码(您可以通过从命令行运行 numpy_test.py 来执行此操作),您的控制台将打印“here”,而不是“Max returned!”。

numpy_ext.cpp:

#include <boost/python/numpy.hpp>
#include <boost/python/module.hpp>
#include <boost/python/def.hpp>
#include <boost/python.hpp>
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <iostream>
#include <stdint.h>
#include "Python.h"
#include "numpy/arrayobject.h"

namespace p = boost::python;
namespace np = boost::python::numpy;
//namespace PyObj = boost::python::object;

void numpy_info(PyObject *  object)
{
    PyArrayObject *array = reinterpret_cast<PyArrayObject*>(object);
    Py_Initialize();
    np::initialize();
    PyObject *elem;    
    std::cout << "here" << std::endl;
    elem = PyArray_Max(array, NPY_MAXDIMS , NULL);  //NPY_MAXDIMS is the same as axis = None in python
    std::cout << "Max returned!" << std::endl;
    int value = PyLong_AsLong(elem);
    std::cout << value << std::endl;
}
BOOST_PYTHON_MODULE(numpy_ext)
{
    using namespace boost::python;
    def("numpy_info", numpy_info);
}

numpy_test.py:

import numpy
import ctypes

a = numpy.array([2,3,1,0])
import numpy_ext
numpy_ext.numpy_info(a)

这是我正在使用的设置文件:

numpy_setup.py:

from distutils.core import setup
from distutils.extension import Extension
import numpy

numpy_ext = Extension(
    'numpy_ext',
    library_dirs=['C:\\local\\boost_1_69_0\\stage\\lib', 'C:\\Users\\jjones\\AppData\\Local\\Programs\\Python\\Python37\\Lib\\site-packages\\numpy\\core\\include\\numpy'],
    sources=['numpy_ext.cpp'],
    libraries=['libboost_python37-vc141-mt-gd-x64-1_69'],
)

setup(
    name='numpy-ext',
    version='0.1',
    include_dirs=[numpy.get_include()],
    ext_modules=[numpy_ext])

标签: cnumpypython-c-api

解决方案


推荐阅读