Wednesday, October 14, 2015

Look before you leap

There are countless reasons to do unsafe memory access.  Here's some help:

import ctypes
import os

if hasattr(ctypes.cdll, "msvcrt"):  #windows branch
    _BUF = ctypes.create_string_buffer('a')

    def _check(address):
            ctypes.cdll.msvcrt.memcpy(_BUF, address, 1)
            return True
        except WindowsError:
            return False

    libc = ctypes.CDLL('')
    libc.write.argtypes = ctypes.c_int, ctypes.c_void_p, ctypes.c_size_t

    _BUF = open('/tmp/_buf', 'w')
    _FD = _BUF.fileno()

    def _check(address):
        rc = libc.write(_FD, address, 1)
        return rc == 1

def is_valid_ptr(address):
    'determines if the passed address (integer) is a valid pointer'
    return _check(address)