Passing a C++ std::Vector to numpy array in Python
Question: I am trying a pass a vector of doubles that I generate in my `C++` code to a
`python` numpy array. I am looking to do some downstream processing in
`Python` and want to use some python facilities, once I populate the numpy
array. One of the biggest things I want to do is to be able to plot things,
and C++ is a bit clumsy when it comes to that. Also I want to be able to
leverage Python's statistical power.

Though I am not very clear as to how to do it. I spent a lot of time going
through the Python C API documentation. I came across a function
PyArray_SimpleNewFromData that apparently can do the trick. I still am very
unclear as far as the overall set up of the code is concerned. I am building
certain very simple test cases to help me understand this process. I generated
the following code as a standlone Empty project in Visual Studio express 2012.
I call this file Project1

    
    
    #include <Python.h>
    #include "C:/Python27/Lib/site-packages/numpy/core/include/numpy/arrayobject.h"
    
    PyObject * testCreatArray()
    {
        float fArray[5] = {0,1,2,3,4};
        npy_intp m = 5;
        PyObject * c = PyArray_SimpleNewFromData(1,&m,PyArray_FLOAT,fArray);
        return c; 
    }
    

My goal is to be able to read the PyObject in Python. I am stuck because I
don't know how to reference this module in Python. In particular how do I
import this Project from Python, I tried to do a import Project1, from the
project path in python, but failed. Once I understand this base case, my goal
is to figure out a way to pass the vector container that I compute in my main
function to Python. I am not sure how to do that either.

Any experts who can help me with this, or maybe post a simple well contained
example of some code that reads in and populates a numpy array from a simple
c++ vector, I will be grateful. Many thanks in advance.


Answer: I came across your post when trying to do something very similar. I was able
to cobble together a solution, the entirety of which is [on my
Github](https://github.com/Frogee/PythonCAPI_testing). It makes two C++
vectors, converts them to Python tuples, passes them to Python, converts them
to NumPy arrays, then plots them using Matplotlib.

Much of this code is from the Python Documentation.

Here are some of the important bits from the .cpp file :

    
    
     //Make some vectors containing the data
     static const double xarr[] = {1,2,3,4,5,6,7,8,9,10,11,12,13,14};
     std::vector<double> xvec (xarr, xarr + sizeof(xarr) / sizeof(xarr[0]) );
     static const double yarr[] = {0,0,1,1,0,0,2,2,0,0,1,1,0,0};
     std::vector<double> yvec (yarr, yarr + sizeof(yarr) / sizeof(yarr[0]) );
    
     //Transfer the C++ vector to a python tuple
     pXVec = PyTuple_New(xvec.size()); 
     for (i = 0; i < xvec.size(); ++i) {
          pValue = PyFloat_FromDouble(xvec[i]);
          if (!pValue) {
               Py_DECREF(pXVec);
               Py_DECREF(pModule);
               fprintf(stderr, "Cannot convert array value\n");
               return 1;
          }
          PyTuple_SetItem(pXVec, i, pValue);
     }
    
     //Transfer the other C++ vector to a python tuple
     pYVec = PyTuple_New(yvec.size()); 
     for (i = 0; i < yvec.size(); ++i) {
          pValue = PyFloat_FromDouble(yvec[i]);
          if (!pValue) {
               Py_DECREF(pYVec);
               Py_DECREF(pModule);
               fprintf(stderr, "Cannot convert array value\n");
               return 1;
          }
          PyTuple_SetItem(pYVec, i, pValue); //
     }
    
     //Set the argument tuple to contain the two input tuples
     PyTuple_SetItem(pArgTuple, 0, pXVec);
     PyTuple_SetItem(pArgTuple, 1, pYVec);
    
     //Call the python function
     pValue = PyObject_CallObject(pFunc, pArgTuple);
    

And the Python code:

    
    
    def plotStdVectors(x, y):
        import numpy as np
        import matplotlib.pyplot as plt
        print "Printing from Python in plotStdVectors()"
        print x
        print y
        x = np.fromiter(x, dtype = np.float)
        y = np.fromiter(y, dtype = np.float)
        print x
        print y
        plt.plot(x, y)
        plt.show()
        return 0
    

Which results in the plot that I can't post here due to my reputation, but is
[posted on my blog post
here](http://codextechnicanum.blogspot.com/2013/12/embedding-python-in-c-
converting-c.html).

