FacundoGFlores
FacundoGFlores

Reputation: 8118

Wrong return using ctypeslib from numpy

These are the C files:

addone.h

#ifndef __ADDONE
#define __ADDONE
void  addone(float *in_data, int size);
#endif

addone.c

void addone(float *in_data, int size)
{
  int i = 0;
  for(int i = 0; i < size; i++)
  {
    in_data[i] = in_data[i] + 1;
  }
}

And I am trying to use this function with ctypes from numpy:

import numpy as np
import numpy.ctypeslib as npct
from ctypes import c_int

array_1d_float = npct.ndpointer(dtype=np.float, ndim=1, flags="CONTIGUOUS")
libcd = npct.load_library("libaddone", ".")
libcd.addone.restype = None
libcd.addone.argtypes = [array_1d_float, c_int]

def addone(in_array):
    return libcd.addone(in_array, len(in_array))

def main():
    out = np.array([1,2,3], dtype=np.float)
    print out
    addone(out)
    print out

if __name__ == "__main__":
    main()

But when I run this file I obtain wrong results:

python test.py
[1. 2. 3.]
[24.00000378   2.00000047   3.     ]

How to fix it?

Upvotes: 1

Views: 159

Answers (1)

Binary Birch Tree
Binary Birch Tree

Reputation: 15728

You can fix this by using:

void addone(double *in_data, int size)

Instead of:

void addone(float *in_data, int size)

As explained in https://stackoverflow.com/a/16964006, np.float is an alias for 's built-in float type, which corresponds to a double in .

Before replacing float with double:

$ python test.py
[ 1.  2.  3.]
[ 24.00000378   2.00000047   3.        ]

After replacing float with double and recompiling the library:

$ python test.py
[ 1.  2.  3.]
[ 2.  3.  4.]

Alternatively, you could leave your code unchanged and use np.float32 instead of np.float in your code.

Upvotes: 2

Related Questions