[C++-sig] Trouble converting data from numpy.array to c++

QUILLET Jean-Charles jean-charles.quillet at alyotech.fr
Wed May 12 10:11:40 CEST 2010


Thanks Andreas,

I've found out my solution in pyrap source code (pyrap.googlecode.com). I post it here as it can be usefull for others:

#include <numpy/ndarrayobject.h>

int type = PyArray_TYPE(anArray.ptr());

for (unsigned i = 0; i < 3; ++ i)
{
	void * buffer = PyArray_GETPTR1(anArray.ptr(), i);
	double val = 0;
	switch (type) 
	{
		case NPY_BOOL:
			val = (*(::npy_bool*)buffer != 0);
			break;
				
		case NPY_INT8:
			val = int(*(::npy_int8*)buffer);
			break;
		
		case NPY_UINT8:
			val = uint(*(::npy_uint8*)buffer);
			break;
	
		case NPY_INT16:
			val = int(*(::npy_int16*)buffer);
			break;

		case NPY_UINT16:
			val = uint(*(::npy_int16*)buffer);
			break;

		case NPY_INT32:
			val = int(*(::npy_int32*)buffer);
			break;

		case NPY_UINT32:
			val = uint(*(::npy_int32*)buffer);
			break;

		case NPY_INT64:
			val = uint(*(::npy_int64*)buffer);
			break;

		case NPY_UINT64:
			val = uint(*(::npy_int64*)buffer);
			break;

		case NPY_FLOAT32:
			val = float(*(::npy_float32*)buffer);
			break;

		case NPY_FLOAT64:
			val = double(*(::npy_float64*)buffer);
			break;
	}
}	

Jean-Charles

-----Message d'origine-----
De : Andreas Kloeckner [mailto:lists at informa.tiker.net] 
Envoyé : mardi 11 mai 2010 17:46
À : QUILLET Jean-Charles; 'cplusplus-sig at python.org'
Objet : Re: [C++-sig] Trouble converting data from numpy.array to c++

Hi Jean-Charles,

On Tue, 11 May 2010 11:32:08 +0200, QUILLET Jean-Charles <jean-charles.quillet at alyotech.fr> wrote:
> I've got this problem I cannot solve. I've a c++ application from which I create an array sending to python this string:
> 
> anArray = numpy.array((1, 2, 3))
> 
> After extracting the symbol "anArray" from the directory in a boost::python::object, I'm trying to extract the values in C++:
> 
> int val = bp::extract<int>(anArray[0]);
> 
> It doesn't work and raise the error:

This is probably not what you wanted to hear, but my PyUblas package
solves your problem. :)

http://mathema.tician.de/software/pyublas

HTH,
Andreas


More information about the Cplusplus-sig mailing list