Created
April 4, 2012 15:22
-
-
Save clayg/2302665 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import ctypes | |
from ctypes import cdll, util | |
import os | |
libc = cdll.LoadLibrary(util.find_library('c')) | |
_get_errno_loc = libc.__errno_location | |
_get_errno_loc.restype = ctypes.POINTER(ctypes.c_int) | |
def get_errno(): | |
return _get_errno_loc().contents.value | |
def errcheck(ret, func, args): | |
if ret == -1: | |
e = get_errno() | |
msg = os.strerror(e) | |
raise OSError(e, msg) | |
return ret | |
_pwrite = libc.pwrite | |
_pwrite.argtypes = [ctypes.c_int, ctypes.c_void_p, ctypes.c_size_t, | |
ctypes.c_uint64] | |
_pwrite.errcheck = errcheck | |
_pread = libc.pread | |
_pread.argtypes = [ctypes.c_int, ctypes.c_void_p, ctypes.c_size_t, | |
ctypes.c_uint64] | |
_pwrite.errcheck = errcheck | |
def pwrite(fd, buff, count=None, offset=0): | |
if count is None: | |
count = len(buff) | |
_pwrite(fd, buff, count, offset) | |
def pread(fd, count, offset=0): | |
buff = ctypes.create_string_buffer(count) | |
_bytes_read = _pread(fd, buff, count, offset) | |
return buff.value | |
class DirectFile(file): | |
def pwrite(self, buff, count=None, offset=0): | |
pwrite(self.fileno(), buff, count, offset) | |
def pread(self, count, offset=0): | |
return pread(self.fileno(), count, offset) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment