Skip to content

Instantly share code, notes, and snippets.

@sphaero
Created June 4, 2015 08:40
Show Gist options
  • Select an option

  • Save sphaero/3ff5a72e699d828306ec to your computer and use it in GitHub Desktop.

Select an option

Save sphaero/3ff5a72e699d828306ec to your computer and use it in GitHub Desktop.
Python passing object by reference through a socket
#!/usr/bin/python3
# WARNING: This is a very nast hack into passing the pointer of an
# object through a socket thus bypassing any copy. The garbage
# collector can remove an object before its being received so you
# should know what you are doing!
import threading
from PIL import Image, ImageDraw, ImageTk
import zmq
import time
import ctypes
import random
def zcreate_pipe(ctx, hwm=1000):
backend = zmq.Socket(ctx, zmq.PAIR)
frontend = zmq.Socket(ctx, zmq.PAIR)
backend.set_hwm(hwm)
frontend.set_hwm(hwm)
# close immediately on shutdown
backend.setsockopt(zmq.LINGER, 0)
frontend.setsockopt(zmq.LINGER, 0)
endpoint = "tcp://127.0.0.1:32323"
#endpoint = "ipc://zactor-%04x-%04x\n"\
# %(random.randint(0, 0x10000), random.randint(0, 0x10000))
while True:
try:
frontend.bind(endpoint)
except:
endpoint = "ipc://zactor-%04x-%04x\n"\
%(random.randint(0, 0x10000), random.randint(0, 0x10000))
else:
break
backend.connect(endpoint)
return (frontend, backend)
def create_img():
global outs
count = 0
while count < 10:
img = Image.new("RGB", (200,600), (15,15,15))
print("Thread:", img, id(img))
outs.send_unicode(str(id(img)))
#del(img) # uncomment this to see the effect of
# the garbage collector intervening
time.sleep(10)
ins, outs = zcreate_pipe(zmq.Context())
thread = threading.Thread(target=create_img)
thread.start()
while True:
msg = ins.recv()
print("Main:", msg, int(msg))
rimg = ctypes.cast(int(msg), ctypes.py_object).value
print("Main:", rimg, id(rimg))
rimg.save("/tmp/test.png", "PNG")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment