boost python - nullptr while extracting ndarray

夙愿已清 提交于 2019-12-24 07:07:22

问题


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();

And example py script:

MyModule.py

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

However it ends with error:

read access violation BOOST_NUMPY_ARRAY_API was nullptr

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?


回答1:


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

Notice the beginning of the official tutorial:

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();

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



来源:https://stackoverflow.com/questions/54904448/boost-python-nullptr-while-extracting-ndarray

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!