简体   繁体   中英

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

A DLL provides a pointer to a 1D array in my C code like this:

__int16 *data = Msg_RowAt(surfaceMsg, rowIdx);

//access the values like this
data[iterator]

I'm building a Python project where I need to access the values of the same array. I've tried the following but get an access violation when I try iterate 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]))

I'm accessing the wrong memory location but I'm not too sure what I've done wrong. Can anyone see what I'm doing wrong?

You can define restype :

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

Then, you can randomly access to each element:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM