How to read from pointer address in Python?

前端 未结 3 1705
南方客
南方客 2021-01-20 19:27

I want to read in a Python script a number of bytes starting from a specific address. E.g., I want to read 40000 bytes starting from 0x561124456.

The pointer is give

3条回答
  •  感动是毒
    2021-01-20 20:02

    Once I got a pointer of memory location from C, I found "list(listSize * listDataType).from_address(memoryPointer)" created a internal copy of C memeory. If the data in memory is huge, Python takes a long time to create a list object by using internal copy. To avoid internal copy, I used the ctypelib.as_array in python:

    import ctypes
    import binascii
    import numpy as np
    
    myCfunslib.getData.restype = ctypes.c_void_p
    #myCfunslib.getData.restype=ctypes.POINTER(ctypes.c_ubyte)#no need to cast
    dataSize = 1092 * 1208
    #call the c function to get the data memory pointer
    cMemoryPointer = myCfunslib.getData();
    newpnt = ctypes.cast(cMemoryPointer, ctypes.POINTER(ctypes.c_ubyte))
    # and construct an array using this data
    DataBytes = np.ctypeslib.as_array(newpnt, (dataSize,)) #no internal copy
    print "the mid byte of the data in python side is ", DataBytes[dataSize/2]
    

提交回复
热议问题