home *** CD-ROM | disk | FTP | other *** search
/ Hackers Magazine 57 / CdHackersMagazineNr57.iso / Software / Multimedia / k3d-setup-0.7.11.0.exe / lib / site-packages / OpenGL / arrays / _strings.py < prev    next >
Encoding:
Python Source  |  2008-12-07  |  1.9 KB  |  68 lines

  1. """Run-time calculation of offset into Python string structure
  2.  
  3. Does a scan to find the digits of pi in a string structure
  4. in order to produce an offset that can be used to produce 
  5. data-pointers from Python strings.
  6.  
  7. Porting note:
  8.     
  9.     Currently this uses id( str a ) to get the base address
  10.     of the Python string.  Python implementations where id( a )
  11.     is *not* the memory address of the string will not work!
  12. """
  13. import ctypes
  14. PI_DIGITS = '31415926535897931'
  15.  
  16. def calculateOffset( ):
  17.     """Calculates the data-pointer offset for strings
  18.     
  19.     This does a sequential scan for 100 bytes from the id
  20.     of a string to find special data-value stored in the
  21.     string (the digits of PI).  It produces a dataPointer
  22.     function which adds that offset to the id of the 
  23.     passed strings.
  24.     """
  25.     finalOffset = None
  26.     a = PI_DIGITS
  27.     # XXX NOT portable across Python implmentations!!!
  28.     initial = id(a)
  29.     targetType = ctypes.POINTER( ctypes.c_char )
  30.     for offset in range( 100 ):
  31.         vector = ctypes.cast( initial+offset,targetType )
  32.         allMatched = True
  33.         for index,digit in enumerate( a ):
  34.             if vector[index] != digit:
  35.                 allMatched = False
  36.                 break
  37.         if allMatched:
  38.             finalOffset = offset
  39.             break
  40.     if finalOffset is not None:
  41.         def dataPointer( data ):
  42.             """Return the data-pointer from the array using calculated offset
  43.             
  44.             data -- a Python string
  45.             
  46.             Returns the raw data-pointer to the internal buffer of the passed string
  47.             """
  48.             if not isinstance( data, str ):
  49.                 raise TypeError(
  50.                     """This function can only handle Python strings!  Got %s"""%(
  51.                         type(data),
  52.                     )
  53.                 )
  54.             return id(data) + finalOffset
  55.         # just for later reference...
  56.         dataPointer.offset = finalOffset 
  57.         return dataPointer
  58.     raise RuntimeError(
  59.         """Unable to determine dataPointer offset for strings!"""
  60.     )
  61.  
  62. dataPointer = calculateOffset()
  63.  
  64. if __name__ == "__main__":
  65.     a  = 'this'
  66.     print id(a), dataPointer( a ), dataPointer(a) - id(a)
  67.     
  68.