c - 运行 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])
解决方案
推荐阅读
- publish-subscribe - 是否可以在 gcloud PubSub 中提供一条消息来增加同一订阅的实例
- deep-learning - 运行到 CUDA 内存不足
- json - 我如何压缩更大的数据(5MB JSON)并作为生产者发送到 Kinesis 流并在使用时解压缩它?
- javascript - 我的控制台中跨站点 cookie 的这些警告是什么?
- flutter - http get call api 不更新响应。它显示先前的响应
- google-cloud-platform - 使用 Ansible,如何启动当前停止的 GCP VM 实例?
- neo4j - 在大图中获取特定路径的开始和结束节点
- azure-active-directory - Azure AD 非图库企业应用程序通过 Powershell 脚本
- image-processing - 证明两个灰度图像相同与否
- powershell - 抑制 Powershell 命令的输出