从numpy使用ctypeslib的错误返回

时间:2016-05-12 22:27:20

标签: python c numpy ctypes

这些是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.     ]

如何解决?

1 个答案:

答案 0 :(得分:2)

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

void addone(double *in_data, int size)

而不是:

void addone(float *in_data, int size)

正如https://stackoverflow.com/a/16964006中所述,np.float内置float类型的别名,对应double中的float 3}}

在用double替换$ python test.py [ 1. 2. 3.] [ 24.00000378 2.00000047 3. ] 之前:

float

double替换$ python test.py [ 1. 2. 3.] [ 2. 3. 4.] 并重新编译库:

np.float32

或者,您可以保持代码不变,并在代码中使用np.float代替create function FunctionNeeded( value_from int, value_to int, number_of_values int, something_else int) returns setof int as $$ select floor(random() * (1+$2-$1))::int + $1 from generate_series(1,$3) $$ language sql;