/llpython/pyaddfunc.py

https://github.com/blep/llvmpy · Python · 40 lines · 29 code · 6 blank · 5 comment · 4 complexity · f9f5d520c55f925518c2d95996a0deff MD5 · raw file

  1. # ______________________________________________________________________
  2. import ctypes
  3. # ______________________________________________________________________
  4. class PyMethodDef (ctypes.Structure):
  5. _fields_ = [
  6. ('ml_name', ctypes.c_char_p),
  7. ('ml_meth', ctypes.c_void_p),
  8. ('ml_flags', ctypes.c_int),
  9. ('ml_doc', ctypes.c_char_p),
  10. ]
  11. PyCFunction_NewEx = ctypes.pythonapi.PyCFunction_NewEx
  12. PyCFunction_NewEx.argtypes = (ctypes.POINTER(PyMethodDef),
  13. ctypes.c_void_p,
  14. ctypes.c_void_p)
  15. PyCFunction_NewEx.restype = ctypes.py_object
  16. cache = {} # Unsure if this is necessary to keep the PyMethodDef
  17. # structures from being garbage collected. Assuming so...
  18. def pyaddfunc (func_name, func_ptr, func_doc = None):
  19. global cache
  20. if bytes != str:
  21. func_name = bytes(ord(ch) for ch in func_name)
  22. key = (func_name, func_ptr)
  23. if key in cache:
  24. _, ret_val = cache[key]
  25. else:
  26. mdef = PyMethodDef(bytes(func_name),
  27. func_ptr,
  28. 1, # == METH_VARARGS (hopefully remains so...)
  29. func_doc)
  30. ret_val = PyCFunction_NewEx(ctypes.byref(mdef), 0, 0)
  31. cache[key] = (mdef, ret_val)
  32. return ret_val
  33. # ______________________________________________________________________
  34. # End of pyaddfunc.py