Skip to content Skip to sidebar Skip to footer

Python: Writing To Memory In A Single Operation

I'm writing a userspace driver for accessing FPGA registers in Python 3.5 that mmaps the FPGA's PCI address space, obtains a memoryview to provide direct access to the memory-mappe

Solution 1:

Perhaps this would work as needed?

mv[address:address+4] = struct.pack("<I", data)

Update:

As seen from the comments, the code above does not solve the problem. The following variation of it does, however:

mv_as_int = mv.cast('I')
mv_as_int[address/4] = data

Unfortunately, precise understanding of what happens under the hood and why exactly memoryview behaves this way is beyond the capabilities of modern technology and will thus stay open for the researchers of the future to tackle.

Solution 2:

You could try something like this:

def__init__(self,offset,size=0x10000):
    self.offset = offset
    self.size = size
    
    mmap_file = os.open('/dev/mem', os.O_RDWR | os.O_SYNC)
    mem = mmap.mmap(mmap_file, self.size,
                    mmap.MAP_SHARED,
                    mmap.PROT_READ | mmap.PROT_WRITE,
                    offset=self.offset)
    os.close(mmap_file)
    self.array = np.frombuffer(mem, np.uint32, self.size >> 2)
    
defwread(self,address):
    idx = address >> 2
    return_val = int(self.array[idx])
    return return_val
    
defwwrite(self,address,data):
    idx = address >> 2
    self.array[idx] = np.uint32(data)

Post a Comment for "Python: Writing To Memory In A Single Operation"