代码之家  ›  专栏  ›  技术社区  ›  vivek patel

在python中使用ctypes和mmap进行c++代码转换

  •  0
  • vivek patel  · 技术社区  · 6 年前

    int fd_vdma = open("/dev/mem", O_RDWR|O_SYNC);  // open uiox device for vdma access
        if (fd_vdma < 1) {
            printf("Invalid mem device file\n");
        }
        // mmap the vdma device for vdma access
    
        unsigned int *ptr_vdma;
        ptr_vdma = (unsigned int*)mmap(NULL, VDMA_MAP_SIZE,PROT_READ|PROT_WRITE, 
        MAP_SHARED, fd_vdma, VDMA_ADDR);
        printf("DMA 1 virtual address: 0x%08x \n",ptr_vdma);
    
        *(ptr_vdma+5) = FRBUF_ADDR_0;
        *(ptr_vdma+7) = 2;  // use internal fifos to trigger xfer
        *(ptr_vdma+8) = 20480;
        *(ptr_vdma+6) = (75 << 16) + (HORIZ_PIXELS_SMALL+75);
        *(ptr_vdma+0x0D) = 200;  // no. FIFO threshhold .. max.. 240
    

    到目前为止我已经做到了,

    # vdm memory check
    try:
        fd_vdm_path = "/dev/mem"
        mode = "rb+"
        fd_vdm =  open(fd_vdm_path, mode)
        # print(fd_vdm.fileno())
        print("[INFO] " + fd_vdm_path + " checked")
    
    except Exception as error:
        print("{}".format(error))
    
     # mmap the VDMA device for VDM access
    vdma_buf = mmap.mmap(fd_vdm.fileno(), int(VDMA_MAP_SIZE), 
    mmap.MAP_SHARED, mmap.PROT_READ|mmap.PROT_WRITE, 0)
    
    ptr_vdm = ctypes.c_uint.from_buffer(vdma_buf)
    print(type(ctypes.addressof(ptr_vdm)))
    print("[INFO] " + fd_vdm_path + " has allocated virtual address : " + 
    hex(ctypes.addressof(ptr_vdm)))
    

    但我一直停留在这里,我不知道如何在python中执行下面的操作。

    *(ptr_vdma+5) = FRBUF_ADDR_0;
    *(ptr_vdma+7) = 2;  // use internal fifos to trigger xfer
    *(ptr_vdma+8) = 20480;
    *(ptr_vdma+6) = (75 << 16) + (HORIZ_PIXELS_SMALL+75);
    *(ptr_vdma+0x0D) = 200;  // no. FIFO threshhold .. max.. 240
    

    我已经试过了 vdma_buf.write(FRBUF_ADDR_0) 但它不工作,我在网上找不到任何东西(可能是我没有搜索好)

    1 回复  |  直到 6 年前
        1
  •  3
  •   Igor    6 年前

    你可以用 memoryview struct.pack :

    ...
    mm = memoryview(vdma_buf)
    
    mm[5*4:6*4] = struct.pack("I", FRBUF_ADDR_0)
    mm[7*4:8*4] = struct.pack("I", 2)
    mm[8*4:9*4] = struct.pack("I", 20480)
    mm[6*4:7*4] = struct.pack("I", (75 << 16) + (HORIZ_PIXELS_SMALL+75))
    mm[0x0D*4:0x0E*4] = struct.pack("I", 200)
    

    .

    假设你想在索引处写一个无符号int N . 首先,你打电话 struct.pack("I", ...) 获取int的字节表示。然后必须计算目标内存地址。因为unsigned int的大小是4字节,所以地址等于 N*4个

    memoryview支持 切片

    mm[StartAddress:EndAddress] = BytesYouWantToWrite
    

    其中StartAddress等于N*4,EndAddress为(N+1)*4