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++?

3
  • have you initialized PyArray_API? Commented Nov 7, 2017 at 6:31
  • What's the proper way to initialized PyArray_API, can't find any suggestions from docs.scipy.org/doc/numpy/reference/c-api.array.html Commented Nov 7, 2017 at 7: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: stackoverflow.com/a/47027598/5769463 Commented Nov 7, 2017 at 7:45

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.