0

I want to embed Python into C++(Qt5),the function defined in .py return a ndarray,just like below:

import numpy as np
def add(a,b):
    c=np.arange(20,dtype=np.int)
    return c

my code in C++ looks like:

int add(int a,int b){
    Py_Initialize();
    PyObject* pModule = PyImport_ImportModule("test001");
    PyObject* pFunc = PyObject_GetAttrString(pModule, "add");
    PyObject* pArgs = PyTuple_New(2);
    PyTuple_SetItem(pArgs, 0, Py_BuildValue("i", a));
    PyTuple_SetItem(pArgs, 1, Py_BuildValue("i", b));

    PyObject* pReturn;
    PyArrayObject *arrReturn;
    pReturn = PyEval_CallObject(pFunc, pArgs);
    //bool ok=PyArg_ParseTuple(pReturn, "O!", &PyArray_Type, &arrReturn);
    arrReturn = (PyArrayObject *)(pReturn);
    int x = *((int *)PyArray_GETPTR1(arrReturn, 0));

Segfault raised when running PyArg_ParseTuple(),then I tried TypeCast to PyArrayObject*,but still can't access the right data(x could be some random values).What is the right way to access numpy array in C++?

Dason
  • 16
  • 3
  • have you initialized `PyArray_API`? – ead Nov 07 '17 at 06:31
  • What's the proper way to initialized PyArray_API, can't find any suggestions from https://docs.scipy.org/doc/numpy/reference/c-api.array.html – Dason Nov 07 '17 at 07:27
  • I answered a similar question some time ago, it maybe not the proper way, but at least you can verify that this is your issue: https://stackoverflow.com/a/47027598/5769463 – ead Nov 07 '17 at 07:45

0 Answers0