Skip to content

Instantly share code, notes, and snippets.

@redbo
Created November 30, 2011 08:23
Show Gist options
  • Save redbo/1408423 to your computer and use it in GitHub Desktop.
Save redbo/1408423 to your computer and use it in GitHub Desktop.
import ctypes
import os
import mmap
class Record(ctypes.Structure):
_fields_ = [('index', ctypes.c_uint64),
('key_length', ctypes.c_uint16),
('key', ctypes.c_char * 256)]
RECORD_COUNT = 256
file_size = ctypes.sizeof(Record) * RECORD_COUNT
with open('somefile', 'w+b') as fp:
os.ftruncate(fp.fileno(), file_size)
mem = mmap.mmap(fp.fileno(), file_size)
array = (Record * RECORD_COUNT).from_buffer(mem)
for i, item in enumerate(array):
item.index = i
item.key = 'item ' + str(i)
item.key_length = len(item.key)
mem.flush()
mem.close()
with open('somefile', 'r+b') as fp:
mem = mmap.mmap(fp.fileno(), file_size)
array = (Record * RECORD_COUNT).from_buffer(mem)
for i, item in enumerate(array):
assert(i == item.index)
assert('item ' + str(i) == item.key)
assert(len('item ' + str(i)) == item.key_length)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment