Skip to content

Instantly share code, notes, and snippets.

@jonashaag
Created April 8, 2020 09:07
Show Gist options
  • Save jonashaag/b3281697837cde458e11c6dbd48bdb41 to your computer and use it in GitHub Desktop.
Save jonashaag/b3281697837cde458e11c6dbd48bdb41 to your computer and use it in GitHub Desktop.
Pickle ctypes _FuncPtr
class PickleableCtypesFuncPtr:
"""A version of a ctypes._FuncPtr that can be pickled. The shared library
must be available in the depickling environment.
"""
def __init__(self, dll_type, lib, name):
self.__setstate__((dll_type, lib, name))
def __setstate__(self, state):
self.state = state
dll_type, lib, func = self.state
dll_loader = getattr(ctypes, dll_type)
self.funcptr = dll_loader(lib)[func]
def __getstate__(self):
return self.state
def __call__(self, *args):
return self.funcptr(*args)
_libc_name = ctypes.util.find_library("c")
_usleep = PickleableCtypesFuncPtr('PyDLL', _libc_name, 'usleep')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment