[Numpy-discussion] Numpi array and typemap

Bill Spotz wfspotz at sandia.gov
Mon Mar 15 13:42:50 EDT 2010


Michel,

A couple observations:

1) I don't see anything in your interface file for which numpy.i would  
be helpful.  Is that for something else not shown?

2) When you call PyArray_SimpleNewFromData(), the data buffer pointer  
argument should be cast to (void*).  I am surprised the compiler  
didn't complain, and if it didn't, the results might be unpredictable.

3) Your getContainer() prototype has inconsistent return type in the  
two places you declare it.  One way to avoid this with functions you  
define in your interface file AND want to be wrapped is with %inline:

   %inline template<class T> Container<T> getContainer() { ... }

4) Are you absolutely sure that size_t is unsigned int on your system?

If none of these help, you will need to debug.  First by looking at  
the generated code in, I presume, Foo_wrap.cxx, then maybe with print  
statements added directly to the wrapper, and then with a real  
debugger.  When I compile with debugging symbol tables, I can get "gdb  
--args python foo_script.py" to work.

On Mar 15, 2010, at 4:45 AM, Michel Dupront wrote:

> Hello,
>
> I am trying to do what was suppose to be a very easy
> exercice. It consists in converting a C++ class Container into a
> numpy array as show below using typename
> My problem is that if I make the method getContainer run from
> python I will get a numpy array as expected by with wrong values.
> I guess I have a memory problem but I do not understand exactly
> wwhat is going on.
> I was hoping that somebody could help me with that and maybe
> tell me how to use the PyArray_SimpleNewFromData macro.
>
> Thanks
>
>
> %module Foo
> %{
> #define SWIG_FILE_WITH_INIT
> #include "container.h"
> template <class T> Container<T> getContainer()
> {
> ... C Container construction that will have a pointer to  
> (1,2,3,4,5)...
> return C;
> }
> %}
>
> %typedef unsigned int size_t;
> %include "numpy.i"
> %init %{
> import_array();
> %}
>
> template <class T> class Container
> {
> public:
> Container(size_t length, T* pfirst_value);
> size_t lentgh() { ... return the lentgh ...}
> T* ptr() { ... return pointer to the first value ... }
> };
>
> %template(cN) Container<size_t>;
>
> %typemap(python,out) Container<size_t>
> {
> npy_intp dims[] = { 5 };
> PyObject* obj = PyArray_SimpleNewFromData (1,dims,PyArray_UINT, 
> $1.ptr());
> $result = obj;
> }
>
> template <class T> navlib::array<T> getContainer();
> %template(getContainerN ) getContainer<size_t>;

** Bill Spotz                                              **
** Sandia National Laboratories  Voice: (505)845-0170      **
** P.O. Box 5800                 Fax:   (505)284-0154      **
** Albuquerque, NM 87185-0370    Email: wfspotz at sandia.gov **









More information about the NumPy-Discussion mailing list