Skip to content

Instantly share code, notes, and snippets.

@clayg
Created April 4, 2012 15:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save clayg/2302665 to your computer and use it in GitHub Desktop.
Save clayg/2302665 to your computer and use it in GitHub Desktop.
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