簡體   English   中英

如何使用 ctypes 和 Python 從 C dll 數組指針獲取值

[英]How do I get values from a C dll array pointer using ctypes and Python

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]))

我正在訪問錯誤的 memory 位置,但我不太確定我做錯了什么。 誰能看到我做錯了什么?

您可以定義restype

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

然后,您可以隨機訪問每個元素:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM