在提取ndarray时提升python-nullptr [英] boost python - nullptr while extracting ndarray

查看:202
本文介绍了在提取ndarray时提升python-nullptr的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个C ++代码,可以使用boost_python包执行python脚本.只要我从python中提取int,字符串或其他非数组变量,一切都很好.但是,我必须提取一个numpy::ndarray并将其转换为cpp vector.我尝试如下:

I have a C++ code which execute python script with boost_python package. Everything is fine, as longa as I extract int, string, or other not-array variables from python. However I have to extract a numpy::ndarray and convert it to cpp vector. I tried as follow:

main.cpp

#include <iostream>
#include <boost/python.hpp>
#include <boost/python/numpy.hpp>

using namespace boost::python;

int main()
double t_end=7
    try
    {
    Py_Initialize();
    object module = import("__main__");
    object name_space = module.attr("__dict__");
    exec_file("MyModule.py", name_space, name_space);

    object MyFunc = name_space["MyFunc"];
    object result = MyFunc(t_end);

    auto result_array = extract<numpy::ndarray>(result);
    const numpy::ndarray& ret = result_array();
    int input_size = ret.shape(0);
    double* input_ptr = reinterpret_cast<double*>(ret.get_data());
    std::vector<double> v(input_size);
    for (int i = 0; i < input_size; ++i)
        v[i] = *(input_ptr + i);
}
catch (error_already_set)
{
    PyErr_Print();
}

Py_Finalize();

还有示例py脚本:

MyModule.py

import numpy as np
def MyFunc(t_end):
    result = np.array([2,3,1,t_end])
    return results

但是它以错误结尾:

读取访问冲突 BOOST_NUMPY_ARRAY_API 为nullptr

read access violation BOOST_NUMPY_ARRAY_API was nullptr

我也试图像numpy::ndarray result_array = extract<numpy::ndarray>(result);一样直接声明numpy :: ndarray,但是错误是完全一样的.我已经通过直接从python打印ndarray来检查我的ndarray是否不为空,事实并非如此.在python步骤,一切似乎都是正确的.那么,是什么原因导致违规以及如何解决呢?

I also was trying to declare numpy::ndarray directly like numpy::ndarray result_array = extract<numpy::ndarray>(result); But the error is exactly the same. I've checked if my ndarray is not empty by printing it directly from python, and it is not. At the python step all seems to be correct. So what is causing the violation and how to fix it?

推荐答案

由于您使用的是numpy模块而没有首先对其进行初始化,因此会发生此错误.

That error occurs since you're using the numpy module without first initializing it.

请注意官方

初始化Python运行时和numpy模块.调用失败会导致细分错误:

Initialise the Python runtime, and the numpy module. Failure to call these results in segmentation errors:

namespace np = boost::python::numpy;
int main(int argc, char **argv)
{
  Py_Initialize();
  np::initialize();

您的代码缺少对np::initialize();的调用.

Your code is lacking the call to np::initialize();.

这篇关于在提取ndarray时提升python-nullptr的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆