错误 return 使用来自 numpy 的 ctypeslib

Wrong return using ctypeslib from numpy

这些是 C 文件:

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;
  }
}

我正在尝试将此函数与 numpy 中的 ctypes 一起使用:

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()

但是当我 运行 这个文件时,我得到了错误的结果:

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

如何解决?

您可以使用以下方法解决此问题:

void addone(double *in_data, int size)

而不是:

void addone(float *in_data, int size)

如 , np.float is an alias for 's built-in float type, which corresponds to a double in 中所述。

在将 float 替换为 double 之前:

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

float替换为double并重新编译库后:

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

或者,您可以留下 code unchanged and use np.float32 instead of np.float in your 代码。