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)
相关推荐
Python MSS - 纯Python中使用ctypes的超快速跨平台多屏截图模块
ctypes库的使用 python调用Windows DLL ctypes是Python的一个外部库,提供和C语言兼容的数据类型,可以很方便地调用C DLL中的函数。
演示了 1.字符串入参 2.字符串出参 3.传入变参 比较全面了,python代码直接可用,记得把.so文件加入PYTHONPATH. unit1.pas是lazarus写的共享库代码
这是python2.5以后自带的一个很强大的模块,完美的将c c++于python结合起来
Linux环境下离线安装python打包环境所需要的包
python中调用c库的模块。 安装方法: linux: python setup.py install windows: setup.py install
python-ctypes模块中文帮助文档参照.pdf
python-ctypes模块中文帮助文档.docx
资源分类:Python库 所属语言:Python 资源全名:pyzmq-ctypes-2.1.10.tar.gz 资源来源:官方 安装方法:https://lanzao.blog.csdn.net/article/details/101784059
英文pdf, ctypes: python调用C动态库的接口库
t532.rar 测试代码 https://blog.csdn.net/wowocpp/article/details/105382257 python 调用 C++ dll 32位 64位 问题 ctypes.cdll.LoadLibrary
python ctypes实现查找系统进程和进程里的模块
python ctypes 中文帮助,有助于我们理解ctypes
Python使用ctypes库调用外部DLL[参照].pdf
python库,解压后可用。 资源全名:ctypes_windows_sdk-0.0.8-py2.py3-none-any.whl
python操作tsc打印机打印标签...
楔子 我们知道python的执行效率不是很高,而且由于GIL的原因,导致python不能充分利用多核CPU。一般的解决方式是使用多进程,但是多进程开销...python调用扩展模块的一种比较简单的方式就是使用ctypes这个库,这个库是p
python学习笔记,包含生成编译注释,ctypes
这是一个使用Python ctypes和tkinter模块设计, 用API函数管理电脑其他窗口的工具, 应用了ctypes模块调用API函数, tkinter库实现用户界面。 程序中,用户选择一个窗口,即可更改这个窗口的标题、边框样式、透明度等...
python通过ctypes封装调用c开源音频引擎libsoundio,涉及到ctypes调用,定义复杂结构体,python可变参数封包和拆包等操作