# Adapted from https://naleraphael.github.io/blog/posts/devlog_create_a_builtin_frame_object/ import ctypes P_SIZE = ctypes.sizeof(ctypes.c_void_p) IS_X64 = P_SIZE == 8 P_MEM_TYPE = ctypes.POINTER(ctypes.c_ulong if IS_X64 else ctypes.c_uint) ctypes.pythonapi.PyFrame_New.argtypes = ( P_MEM_TYPE, # PyThreadState *tstate P_MEM_TYPE, # PyCodeObject *code ctypes.py_object, # PyObject *globals ctypes.py_object # PyObject *locals ) ctypes.pythonapi.PyFrame_New.restype = ctypes.py_object # PyFrameObject* ctypes.pythonapi.PyThreadState_Get.argtypes = None ctypes.pythonapi.PyThreadState_Get.restype = P_MEM_TYPE def greet(): print('hello') frame = ctypes.pythonapi.PyFrame_New( ctypes.pythonapi.PyThreadState_Get(), # thread state ctypes.cast(id(greet.__code__), P_MEM_TYPE), # a code object globals(), # a dict of globals locals() # a dict of locals ) print(frame) print(frame.f_back) # <--- Segfaults