I'm playing with Python's C-API. Specifically, I want to see if I can inspect how many elements the value stack currently has. Here's my code:
#include <Python.h>
#include <frameobject.h>
int test() {
PyFrameObject* f = PyEval_GetFrame();
return (int)(f->f_stacktop - f->f_valuestack);
}
I'm not sure whether this can work, but this line exists in Python's source code, so I gave it a try.
This usually results in negative number, something like -547715639
.
So clearly I'm doing it wrong, probably because what'e described in the documentation: "Frame evaluation usually NULLs it (f_stacktop)". What's the right way to do it, or is it even possible?
It's impossible. See this answer.
In short, I should use
(int)(stack_pointer - f->f_valuestack);
However, stack_pointer
is a local varaible inside the _PyEval_EvalFrameDefault function, thus can't be accessed from outside.