简体   繁体   中英

How do I access a numpy array in embedded python from c++?

What would be a good way to access a 2dim numpy array in c++? I've already checked out the numpy/c api and some other posts but that doesn't brought me further. Here's the situation:

I defined in a python file called Testfile.py the following numpy array:

import numpy as np
A = np.array([[1, 2, 3], [1, 2, 3], [1, 2, 3]])

Now, I would like to access this array in c++ to use it for further calculations. Here is what i did so far. Note: For simplicity, i left out error handling and reference counting code snippets.

#define NPY_NO_DEPRECATED_APINPY_1_7_API_VERSION
#define PY_ARRAY_UNIQUE_SYMBOL cool_ARRAY_API
#include <Python.h>
#include <arrayobject.h> // numpy!
#include <iostream>
using namespace std;
#include <stdlib.h>
#include <string>

int main(){

// Name of input-file
char pyfilename[] = "Testfile";

// initilaize python interpreter
Py_Initialize();
import_array(); 

// load input-file
PyObject *pyName = PyUnicode_FromString(pyfilename);
PyObject *pyModule = PyImport_Import(pyName);

// import my numpy array object
char pyarrayname[] = "A";
PyObject *obj = PyObject_GetAttrString(pyModule, pyarrayname);

//------------------------------------------------------------
// The Problem starts here..

// Array Dimensions
npy_intp Dims[] = { PyArray_NDIM(obj) }; // array dimension
Dims[0] = PyArray_DIM(obj, 0); // number of rows
Dims[1] = PyArray_DIM(obj, 1); // number of columns

// PyArray_SimpleNew allocates the memory needed for the array.
PyObject *ArgsArray = PyArray_SimpleNew(2, Dims, NPY_DOUBLE);

// The pointer to the array data is accessed using PyArray_DATA()
double *p = (double *)PyArray_DATA(ArgsArray);

for (int i = 0; i<Dims[0]; i++)
{
    for (int j = 0; j<Dims[1]; j++)
        {
             p[i * Dims[1] + j] = *((int *)PyArray_GETPTR2(obj, i, j));
        }
}
// -----------------------------------------------------------


Py_Finalize();

return 0;
}

I use python 3.6 and MSVC 2015.

EDIT: I added the headers i use and changed the problem formulation a bit.

EDIT: I added the proposed solution strategies provided by Swift and Alan Stokes

After you access array by

double *p = (double*)PyArray_DATA(ArgsArray);
int* pA = (int*)PyArray_DATA(obj);

you can work with it like with array. What are dimensions?

int height = PyArray_DIM(obj, 0);
int width = PyArray_DIM(obj, 1);

Now you can use that pointer to access data in array

for ( int i = 0; y<height; y++) 
{ 
   for (int j = 0; x<width; x++) 
   { 
      p[i * width + j] = pA[i * width + j];
   }
}

Actually, if you just need to copy array, use memcpy or std::copy at this point.

Tbh, I'd considered to use boost.python instead, but it's my own preference.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM