【问题标题】:Wrong return using ctypeslib from numpy使用来自 numpy 的 ctypeslib 错误返回
【发布时间】:2016-05-12 22:27:20
【问题描述】:

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

如何解决?

【问题讨论】:

    标签: python c numpy ctypes


    【解决方案1】:

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

    void addone(double *in_data, int size)
    

    代替:

    void addone(float *in_data, int size)
    

    正如https://stackoverflow.com/a/16964006 中解释的那样,np.float 的内置float 类型的别名,它对应于 中的double

    在将float 替换为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

    【讨论】:

      猜你喜欢
      • 2023-01-11
      • 1970-01-01
      • 2019-07-20
      • 2019-11-22
      • 2018-02-26
      • 1970-01-01
      • 2021-12-20
      • 2020-09-19
      • 1970-01-01
      相关资源
      最近更新 更多