Passing a C++ std::Vector to numpy array in Python

前端 未结 4 696
走了就别回头了
走了就别回头了 2021-02-04 06:13

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 P

4条回答
  •  感情败类
    2021-02-04 06:48

    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. 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 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 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.

提交回复
热议问题