boost python - 提取 ndarray 时的 nullptr

boost python - nullptr while extracting ndarray

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

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

然而它以错误结束:

read access violation BOOST_NUMPY_ARRAY_API was nullptr

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

发生该错误是因为您在使用 numpy 模块时没有首先对其进行初始化。

正式开始通知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();

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

的调用