【问题标题】:How to return ndarray in python3 ctypes?如何在 python3 ctypes 中返回 ndarray?
【发布时间】:2018-08-02 14:11:19
【问题描述】:

我有一个 c++ 函数:

double* hiho() {
  double *res = new double[10];
  return res;
}

一起

from numpy.ctypeslib import ndpointer

mylib.hiho.restype = ndpointer(dtype=ctypes.c_double, shape=(10,))

调用函数时出现如下错误:

ValueError: '<P' is not a valid PEP 3118 buffer format string

我使用 Python 3.6.2

我做错了什么?

【问题讨论】:

    标签: python multidimensional-array ctypes


    【解决方案1】:

    我无法重现您的错误,但这有效。如果这不能帮助您解决问题,请提供可重现的示例:

    test.cpp(Windows)

    #define API __declspec(dllexport) // Windows-specific export
    
    extern "C" API double* hiho() {
      double *res = new double[10];
      for(int i = 0; i < 10; ++i)
          res[i] = .1 * i;
      return res;
    }
    

    test.py

    import ctypes
    from numpy.ctypeslib import ndpointer
    
    mylib = ctypes.CDLL('test')
    mylib.hiho.restype = ndpointer(dtype=ctypes.c_double, shape=(10,))
    print(mylib.hiho())
    

    输出

    [0.  0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9]
    

    【讨论】:

      【解决方案2】:

      我已将 numpy 更新到版本 1.18.1。 现在,这很好用:

      from numpy.ctypeslib import ndpointer
      
      mylib.hiho.restype = ndpointer(dtype=ctypes.c_double, shape=(10,))
      

      简单地更新numpy:

      pip install numpy --upgrade
      

      供您参考:

      在 numpy 1.15.4 中,我使用 *double 或 *int 标记示例时遇到了同样的错误。

      我在 MacOS 上的编译行:

      g++ -c -fPIC -std=c++17 test.cpp -o test.o
      
      g++ -dynamiclib -undefined suppress -flat_namespace test.o -o test.dylib
      

      g++ -c test.cpp -o test.o
      
      g++ -dynamiclib -undefined suppress -flat_namespace test.o -o test.dylib
      

      错误:

      ValueError: '<P' is not a valid PEP 3118 buffer format string
      

      【讨论】:

      • 是的,谢谢,我知道了。那是因为我的名声低。我用 numpy 更新解决了这个问题。我已经更新了我的答案。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-16
      • 2011-03-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多