python LInux下使用ctypes操作内存

ctypes创建的内存不能自动对齐,可以使用如下方法对齐内存:

# _*_ coding:UTF-8

import sys
import time
import os

import ctypes
import ctypes.util

def ctypes_alloc_aligned(size, alignment):
    buf_size = size + (alignment - 1)
    #先使用bytearray函数分配一块内存
    raw_memory = bytearray(buf_size)
    #然后从raw_memory创建一个ctypes对象
    ctypes_raw_type = (ctypes.c_char * buf_size)
    ctypes_raw_memory = ctypes_raw_type.from_buffer(raw_memory)
    #通过ctypes对象的addressof获得内存指针的值
    raw_address = ctypes.addressof(ctypes_raw_memory)
    offset = raw_address % alignment
    #通过内存地址可以得出,对齐内存的偏移量
    offset_to_aligned = (alignment - offset) % alignment
    ctypes_aligned_type = (ctypes.c_char * (buf_size - offset_to_aligned))
    #通过内存的偏移量,创建对齐内存的ctype对象
    ctypes_aligned_memory = ctypes_aligned_type.from_buffer(raw_memory, offset_
to_aligned)
    return ctypes_aligned_memory
libc = ctypes.CDLL(ctypes.util.find_library('c'))
#获得一块4k对齐的内存
buf =ctypes_alloc_aligned(1024*1024, 4096)
#direct io的方式打开块设备文件
#fd = os.open('/dev/loop0', os.O_RDWR|os.O_DIRECT)
fd = os.open('./loop0', os.O_RDWR|os.O_DIRECT)
#fd = open('d:/test.txt', 'a')
#print(dir(libc))
err_code = libc.read(ctypes.c_int(fd), buf, ctypes.c_int(1024*1024))
#把directIO读出的数据放到python的一个字符串变量中:
data = buf.raw[0:err_code]
#写数据
libc.memset(buf, ctypes.c_int(0), ctypes.c_int(1024*1024))
libc.write(ctypes.c_int(fd), buf, ctypes.c_int(1024*1024))
os.close(fd)

 

  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值