2

说,我们在Scheme中有以下代码

(define cc #f)
(define bar 0)

(define (func)
  (print "This should show only once")
  (call/cc (lambda (k) (set! cc k)))
  (print bar)
  (set! bar (+ bar 1)))

(define (g)
  (func)
  (print "This should show multiple times"))

(g)
(cc)

打印类似的东西

This should show only once
0
This should show multiple times
1
This should show multiple times

假设我们想在 Python 中做同样的事情。http://wiki.c2.com/?ContinuationsInPython这种方法不起作用,因为它们只保存代码而不是堆栈。我试图实现我的版本call/cc在 Python 中实现我的版本,保存和恢复堆栈上下文。我不能 100% 确定我是否正确实现了延续逻辑,但这现在并不重要。

我的想法是callcc在构造函数中保存函数调用及其调用者的堆栈和指令指针,Continuation然后在继续的__call__方法中,重置保存的堆栈帧中的指令指针,将当前堆栈帧f_back指针指向保存的堆栈帧并神奇地返回出现在调用的函数中callcc

问题是即使输出traceback.print_stack()显示当前堆栈已被替换,代码仍然执行,就好像我根本没有触及当前堆栈一样。这是我的实现https://ideone.com/kGchEm

import inspect
import types
import ctypes
import sys
import traceback


frameobject_fields = [
    # PyObject_VAR_HEAD
    ("ob_refcnt", ctypes.c_int64),
    ("ob_type", ctypes.py_object),
    ("ob_size", ctypes.c_ssize_t),
    # struct _frame *f_back;      /* previous frame, or NULL */
    ("f_back", ctypes.c_void_p),
    # PyCodeObject *f_code;       /* code segment */
    ("f_code", ctypes.c_void_p),
    # PyObject *f_builtins;       /* builtin symbol table (PyDictObject) */
    ("f_builtins", ctypes.py_object),
    # PyObject *f_globals;        /* global symbol table (PyDictObject) */
    ("f_globals", ctypes.py_object),
    ####
    ("f_locals", ctypes.py_object),
    ("f_valuestack", ctypes.POINTER(ctypes.py_object)),
    ("f_stacktop", ctypes.POINTER(ctypes.py_object)),
    ("f_trace", ctypes.py_object),
    ("f_exc_type", ctypes.py_object),
    ("f_exc_value", ctypes.py_object),
    ("f_exc_traceback", ctypes.py_object),
    ("f_tstate", ctypes.c_void_p),
    ("f_lasti", ctypes.c_int),
]
if hasattr(sys, "getobjects"):
    # This python was compiled with debugging enabled.
    frameobject_fields = [
        ("_ob_next", ctypes.c_void_p),
        ("_ob_prev", ctypes.c_void_p),
    ] + frameobject_fields
class PyFrameObject(ctypes.Structure):
    _fields_ = frameobject_fields


class Continuation:
    def __init__(self, frame):
        self.frame = frame
        self.lasti = frame.f_lasti
        self.lastis = []

        frame = frame.f_back
        while frame is not None:
            self.lastis.append(frame.f_lasti)
            frame = frame.f_back

    def __call__(self):
        print('\nbefore')
        traceback.print_stack()

        cur_frame = PyFrameObject.from_address(id(inspect.currentframe()))
        PyFrameObject.from_address(cur_frame.f_back).ob_refcnt -= 1
        cur_frame.f_back = id(self.frame)
        PyFrameObject.from_address(id(self.frame)).ob_refcnt += 1

        frame = self.frame
        _frame = PyFrameObject.from_address(id(frame))
        _frame.f_lasti = self.lasti + 4

        frame = frame.f_back
        for lasti in self.lastis:
            if len(frame.f_code.co_code) != frame.f_lasti + 2:
                break
            _frame = PyFrameObject.from_address(id(frame))
            _frame.f_lasti = lasti + 4
            frame = frame.f_back

        print('\nafter')
        traceback.print_stack()


def callcc(f):
    f(Continuation(inspect.currentframe().f_back))


cc = None


def func():
    bar = 0
    print("This should show only once")
    def save_cont(k):
        global cc
        cc = k
    callcc(save_cont)
    print(bar)
    bar += 1


def g():
    func()
    print("This should show multiple times")

sys.stderr = sys.stdout
g()
cc()
4

2 回答 2

4

问题在于标准解释器——CPython——是一个堆栈式解释器,即Python函数的每次调用都会导致解释器内部的递归调用。因此,PythonFrameType对象只是C 堆栈帧的视图.f_back这是一个只读属性,这是有充分理由的),没有必要更改f_back指针。

如果您真的想操作堆栈,您将不得不编写一个 C 模块,就像greenlet模块一样。

祝你好运!

于 2018-01-31T01:05:26.863 回答
1

这个答案很好地解释了为什么很难捕获 Python 解释器的状态。这个包为你做。它没有实现 call/cc,但它实现了 longjmp 和 setjmp,这只是一些与 call/cc 不同的语法糖。

于 2020-05-22T00:22:30.327 回答