python调用python-c-api 的ndarray,在提取ndarray时提升python-nullptr

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

#include

#include

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<:ndarray>(result);

const numpy::ndarray& ret = result_array();

int input_size = ret.shape(0);

double* input_ptr = reinterpret_cast(ret.get_data());

std::vector 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<: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?

解决方案

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值