【问题标题】:ndpointer in ctypes structure fieldctypes结构字段中的ndpointer
【发布时间】:2021-07-29 03:45:28
【问题描述】:

我不知道如何将numpy.ndpointer 用作python ctypes 结构中的字段。这是一些基本代码,展示了我如何在不使用 ndpointer 的情况下做到这一点,但我想知道是否可以使用 ndpointer,如果可能的话!

import numpy as np
import ctypes

class MyStruct_Working(ctypes.Structure):
    _fields_ = [
        ('a', ctypes.c_ssize_t),
        ('values', ctypes.POINTER(ctypes.c_double))]
    
    
    def __init__(self, a, values):
        self.a = a
        self.values = values.ctypes.data_as(ctypes.POINTER(ctypes.c_double))

class MyStruct_NotWorking(ctypes.Structure):
    _fields_ = [
        ('a', ctypes.c_ssize_t),
        ('values', np.ctypeslib.ndpointer(dtype=float, flags='C_CONTIGUOUS'))]
    
    
    def __init__(self, a, values):
        self.a = a
        self.values = values

使用上面的代码可以正常工作

m0 = MyStruct_Working(1, np.array([1,2,3]))

但是当我调用它时,我收到以下错误消息

m1 = MyStruct_NotWorking(1, np.array([1,2,3]))
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-19-8435d2743b55> in <module>
----> 1 m1 = MyStruct_NotWorking(1, np.array([1,2,3]))

<ipython-input-17-beb0591858e6> in __init__(self, a, values)
     17     def __init__(self, a, values):
     18         self.a = a
---> 19         self.values = values

TypeError: cannot be converted to pointer

【问题讨论】:

    标签: python numpy ctypes


    【解决方案1】:

    上市[Python.Docs]: ctypes - A foreign function library for Python

    根据[NumPy]: numpy.ctypeslib.ndpointer(dtype=None, ndim=None, shape=None, flags=None)强调是我的):

    ndpointer 实例用于在 restypes 和 argtypes 规范中描述 ndarray

    argtypesrestype 只在函数(调用)的上下文中有意义,也就是应该使用 ndpointer 的时候(例如在网址中)。

    作为一种解决方法,您可以拥有一个 ndpointer 结构成员,但您必须以与 ctypes.POINTER 相同的方式初始化它(在 MyStruct_Working)。但是,请记住,这之后会有一些限制(您不会有索引)。
    我的建议是坚持使用 ctypes.POINTER(ctypes.c_double)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-02
      • 1970-01-01
      相关资源
      最近更新 更多