I have a C++ function returning a std::vector and I want to use it in python, so I'm using the C numpy api:

```
static PyObject *
py_integrate(PyObject *self, PyObject *args){
...
std::vector<double> integral;
cpp_function(integral); // This changes integral
npy_intp size = {integral.size()};
PyObject *out = PyArray_SimpleNewFromData(1, &size, NPY_DOUBLE, &(integral[0]));
return out;
}
```

Here's how I call it from python:

```
import matplotlib.pyplot as plt
a = py_integrate(parameters)
print a
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(a)
print a
```

What happens is: The first print is ok, the values are correct. But when I plot `a`

they are not; in the second print I see very strange values like `1E-308 1E-308 ...`

or `0 0 0 ...`

as an uninitialized memory. I don't understand why the first print is ok.

```
static void DeleteVector(void *ptr)
{
std::cout << "Delete" << std::endl;
vector * v = static_cast<std::vector<double> * >(ptr);
delete v;
return;
}
static PyObject *
cppfunction(PyObject *self, PyObject *args)
{
std::vector<double> *vector = new std::vector<double>();
vector->push_back(1.);
PyObject *py_integral = PyCObject_FromVoidPtr(vector, DeleteVector);
npy_intp size = {vector->size()};
PyArrayObject *out;
((PyArrayObject*) out)->base = py_integral;
return (PyObject*)(out);
}
```

Your `std::vector`

object appears to be local to that function. `PyArray_SimpleNewFromData`

does not make a copy of the data you pass it. It just keeps a pointer. So once your py_integrate function returns, the vector is deallocated. The print works the first time because nothing has written over the freed memory yet, but by the time you get to the next print, something else has used that memory, causing the values to be different.

You need to make a NumPy array that owns its own storage space and then copy the data into it.

Alternatively, allocate your vector on the heap. Then store a pointer to it in a CObject. Provide a destructor that deletes the vector. Then, take a look at the C-level PyArrayObject type. It has a `PyObject *`

member called `base`

. Store your `CObject`

there. Then when the NumPy array is garbage collected, the reference count on this base object will be decremented, and assuming you haven't taken a copy of it elsewhere, your vector will be deleted thanks to the destructor you provided.

You forgot to actually create the PyArray. Try this:

(You didn't post `DeleteVector`

, so I can only hope that it's right)

```
std::vector<double> *vector = new std::vector<double>();
vector->push_back(1.);
PyObject *py_integral = PyCObject_FromVoidPtr(vector, DeleteVector);
npy_intp size = {vector->size()};
PyObject *out = PyArray_SimpleNewFromData(1, &size, NPY_DOUBLE, &((*vector)[0]));
((PyArrayObject*) out)->base = py_integral;
return out;
```

Note: I'm not a C++ programmer, so I can only assume that `&((*vector)[0])`

works as intended with a pointer to a vector. I do know that the vector reallocate its storage area if you grow it, so don't increase its size after getting that pointer or it won't be valid anymore.

You will need to make a copy of the vector, since the vector will go out of scope and the memory will no longer be usable by the time you need it in Python (as stated by kwatford).

One way to make the Numpy array you need (by copying the data) is:

```
PyObject *out = nullptr;
std::vector<double> *vector = new std::vector<double>();
vector->push_back(1.);
npy_intp size = {vector.size()};
out = PyArray_SimpleNew(1, &size, NPY_DOUBLE);
memcpy(PyArray_DATA((PyArrayObject *) out), vector.data(), vector.size());
```

Similar Questions

I have a bz2 compressed binary (big endian) file containing an array of data. Uncompressing it with external tools and then reading the file in to Numpy works: import numpy as np dim = 3 rows = 1000 c

question: is my method of converting a numpy array of numbers to a numpy array of strings with specific number of decimal places AND trailing zeros removed the 'best' way? import numpy as np x = np.a

today I used the numpy array for some calculation and found a strange problem, for example, assume i already imported numpy.arange in Ipython, and I run some scripts as follows: In [5]: foo = arange(

How do I get numpy array into python list? looking for ('foo', 1, 2, 3, 4) series is a numpy array symbol = 'foo' def rowp (symbol,series): rowp=[] series = series[0:4] ss = series.tolist rowp.append(

The function PyObject* PyArray_TypeObjectFromType(int); converts the type number for a NumPy scalar type (NPY_BOOL, NPY_BYTE, ...) to the corresponding type object. How do you do the opposite convers

This is risky business, and I understand the Global Interpreter Lock to be a formidable foe of parallelism. However, if I'm using Numpy's C API (specifically the PyArray_DATA macro on a Numpy array),

I intend to do some computation on numpy arrays in C code. Could someone please point to some document on how to extract the double* C array from a numpy.matrix object? So I could have some C code lik

I'm writing a C extension to my Python program for speed purposes, and running into some very strange behaviour trying to pass in a 3-dimensional numpy array. It works with a 2-dimensional array, but

I have a numpy array D of dimensions 4x4 I want a new numpy array based on an user defined value v If v=2, the new numpy array should be [D D]. If v=3, the new numpy array should be [D D D] How do i i

In my code I have for loop that indexes over a multidimensional numpy array and does some operation using the sub-array that is obtained at each iteration. It looks like this for sub in Arr: #do stuff

I'm trying to efficiently map a N * 1 numpy array of ints to a N * 3 numpy array of floats using a ufunc. What I have so far: map = {1: (0, 0, 0), 2: (0.5, 0.5, 0.5), 3: (1, 1, 1)} ufunc = numpy.fromp

I need to know if it is possible to save a python list as a numPy array.

I have the following array: >>> x = numpy.array([2,4,2,3,1]) >>> x array([2, 4, 2, 3, 1]) I would like an array of ranges of these values. I can create it like this: >>> nu

I would like to convert a multi-dimensional Numpy array into a string and, later, convert that string back into an equivalent Numpy array. I do not want to save the Numpy array to a file (e.g. via the

This question already has an answer here: Print the full numpy array 4 answers I am working with image processing in python and I want to output a variable, right now the variable b is a numpy

I have a question regarding numpys memory views: Suppose we have two arrays with memory: import numpy as np import gc x = np.arange(4*3).reshape(4,3).astype(float) y = (np.arange(5) - 5).astype(float)

I am trying to save a large numpy array and reload it. Using numpy.save and numpy.load, the array values are corrupted/change. The shape and data type of the array pre-saving, and post-loading, are th

I'm trying to build a numpy array of arrays of arrays with the following code below. Which gives me a ValueError: setting an array element with a sequence. My guess is that in numpy I need to declar

I have Python dict containing 4 key value pairs. Each value is a numpy arrays. Now I want to print the whole dict to a csv, forcing to write one numpy array per row. with open(os.path.join(csv, titl

I have a list of numpy vectors of the format: [array([[-0.36314615, 0.80562619, -0.82777381, ..., 2.00876354,2.08571887, -1.24526026]]), array([[ 0.9766923 , -0.05725135, -0.38505339, ..., 0.12187988

I have a three dimensional array img of shape [1200,1600,3] and a two dimensional array labels of shape [1200,1600]. The first array is from an image, the second one is from labels in the image. Locat

What is a faster way of finding unique x,y points (removing duplicates) in a numpy array like: points = numpy.random.randint(0, 5, (10,2)) I thought of converting points to a complex numbers and then

I am trying to understand which is the fastest and safest way to access a NumPy array passed through Cython to a C code. I have the following files: func.c: typedef struct { int nr; double *my_array;

This question already has an answer here: Numpy: cartesian product of x and y array points into single array of 2D points 4 answers Is there an easy way in Numpy to generate an array of number

I need to find if a numpy array is inside other numpy array, but it seems to work different to python lists. I tried to search this question in numpy documentation and internet, but not answer. This i

In my code I usally use numpy arrays to interface between methods and classes. Optimizing the core parts of my program I use cython with c pointers of those numpy arrays. Unforunately, the way I'm cur

I have a dictionary that I need to convert to a NumPy structured array. I'm using the arcpy function NumPyArraytoTable, so a NumPy structured array is the only data format that will work. Based on th

I am new to using the numpy class and I am having problems with manipulating the contents of the array. Here is the code: # finance equation to apply to each element of array for row in cum_ret: for c

[ [ 99 66] [118 67] [119 67] [120 67] [121 67] [121 68] [121 70] [ 95 71] [121 71] [123 98] [133 109] [136 110] [150 126] [153 126] [153 128] [153 129]] I have this numpy array which contains sets of

Using the C API, I would like to create a numpy array containing objects of type Quaternion, which is a class I've written in C++. I already have an array of these (actually a std::vector), and I want

I have a function, processing a 1D numpy array, like this: def f(arr): arr=asarray(arr) #process data as numpy array #... return arr With asarray I allow to call the function with a list as f([4,5,6]

Simple question here about indexing an array to get a subset of its values. Say I have a recarray which holds ages in one space, and corresponding values in another. I also have an array which is my d

I have a given array 'a' as follows: import numpy as np a = np.arange(-100.0, 110.0, 20.0, dtype=float) #increase 20 a = np.tile(a, 4) a = a.reshape(4,11) [[-100. -80. -60. -40. -20. 0. 20. 40. 60. 80

I am new to using NumPy and trying to work with arrays, tried building a 1D,2D and now a 3D array. But I wasn't sure why ndim thinks that this is a 2D array even though it has 3 rows In [26]: c= array

I'd like to make a class extending the numpy array base type, class LemmaMatrix(numpy.ndarray): @classmethod def init_from_corpus(cls, ...): cls(numpy.empty(...)) But apparently, it will not allow mu

I have a numpy array containing: [1, 2, 3] I want to create an array containing: [1, 2, 3, 1] That is, I want to add the first element on to the end of the array. I have tried the obvious: np.concat

how do I calculate that an array of python numpy or me of all the calculate decimals and not skip like. >> A = numpy.array ([[1,2,3], [4,5,6], [7,8,9]]). >> C = numpy.array ([[7,8,9], [1,2

I would like to print numpy array with indentation for debugging. Say I have an array a = numpy.array([[1,2,3,4], [5,6,7,8]]), then simple print(a) will give [[ 63 903 942 952] [185 332 511 893]] Now

I'm exploring wrapping c++ classes with SWIG and passing in data from numpy I can sucessfully pass in a 1d array using the following typemap (float*, IN_ARRAY1, int DIM1) The size of the array is not

I am trying to transform transform a numpy array A into B without using a loop. A=np.array([[1,2,3], [1,3,0], [2,0,0]]) B=np.array([[1,2,3], [1,0,3], [0,2,0]]) So in each row, I want to reorder the e

I would like to return some data from c++ code as a numpy.array object. I had a look at boost::python::numeric, but its documentation is very terse. Can I get an example of e.g. returning a (not very

Consider the following convenient looping idiom. import numpy print shape of x = numpy.array([['a', 'b'], ['c', 'd']]) print x print is, x.shape for row in x: print shape of, row, is, row.shap

I am using a Python (via ctypes) wrapped C library to run a series of computation. At different stages of the running, I want to get data into Python, and specifically numpy arrays. The wrapping I am

We initialize a numpy array with zeros as bellow: np.zeros((N,N+1)) But how do we check whether all elements in a given n*n numpy array matrix is zero. The method just need to return a True if all th

Suppose that I have a structured array of students (strings) and test scores (ints), where each entry is the score that a specific student received on a specific test. Each student has multiple entrie

I have three lists, list1=['10','20','30'] list2=['40','50','60'] list3=['70','80','90'] I want to create a numpy array from these lists. I am using the foloowing code: import numpy as np list1=['10

are there any numpy function or clever use of views to accomplish what the following function do? import numpy as np def permuteIndexes(array, perm): newarray = np.empty_like(array) max_i, max_j = ne

I two numpy arrays, both M by N. X contains random values. Y contains true/false. Array A contains indices for rows in X that need replacement, with the value -1. I want to only replace values where Y

I am attempting to subclass a numpy structured array so that I can add special methods to the subclass. Everything works fine until I retrieve a single index from the array. When this occurs, an objec

I have a numpy array like x=np.array([0,1,2,3,4]) and want to create an array where the value in index 0 is in index 1, index 1 is in index 2, etc. The output I want is y=np.array([0,0,1,2,3]). I