【问题标题】:How do I get values from a C dll array pointer using ctypes and Python如何使用 ctypes 和 Python 从 C dll 数组指针中获取值
【发布时间】:2021-02-04 22:15:38
【问题描述】:

DLL 在我的 C 代码中提供指向一维数组的指针,如下所示:

__int16 *data = Msg_RowAt(surfaceMsg, rowIdx);

//access the values like this
data[iterator]

我正在构建一个 Python 项目,我需要在其中访问同一数组的值。我尝试了以下方法,但在尝试迭代 surfaceData 时遇到访问冲突。

surfaceDataPtr = Msg_RowAt(surfaceMsg, row)
ptr = ctypes.POINTER(ctypes.c_int16)
surfaceData = ctypes.cast(surfaceDataPtr, ptr)
print("ptr: " + str(surfaceData))
print("val: " + str(surfaceData[1]))

我访问了错误的内存位置,但我不太确定我做错了什么。谁能看到我做错了什么?

【问题讨论】:

标签: python dll ctypes


【解决方案1】:

你可以定义restype:

c.Msg_RowAt.restype = ctypes.POINTER(ctypes.c_int16)
surfaceDataPtr = Msg_RowAt(surfaceMsg, row)

然后,你可以随机访问每个元素:

print(surfaceDataPtr[0])
print(surfaceDataPtr[1])
...

【讨论】:

  • 感谢您的示例。我真的不明白如何实现 restype。
  • @Velveteen_Brownie 没有什么可实施的。 Python 没有类型。您只需指定 restype 将是什么。在这种情况下,Python 应该知道 surfaceDataPtr 将是指向 short 变量的 C 指针。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-11-24
  • 2013-04-03
  • 2011-05-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多