Suppose I am writing a C Extension, or embedding the interpreter in a C program,
and I need to print the current floating point number cache pool.
For this, I need to obtain a reference to the interpreter state, which is defined in python3.11/internal/pycore_interp.h
,
and there is a guard macro indicating that it should only be used for building Python itself.
Yet, I still managed to write and compile the following code.
#define Py_BUILD_CORE
#include "Python.h"
#include "pytypedefs.h"
#include "internal/pycore_interp.h"
#include <stdio.h>
void print_list(PyFloatObject *list, int size) {
if (list == NULL) {
printf("Free List is NULL\n");
} else {
printf("%d elements in Free List\n", size);
puts("The 1st one is:");
PyObject_Print((PyObject *)&list[0], stdout, Py_PRINT_RAW);
}
while (list->ob_base.ob_type) {
list = list->ob_base.ob_type;
PyObject_Print((PyObject *)list, stdout, Py_PRINT_RAW);
puts("");
printf("(%f)\n", list->ob_fval);
}
}
int main() {
Py_Initialize();
// Creating some random dummy floats
//
PyObject *fobj_1 = PyFloat_FromDouble(233.233);
PyObject *fobj_2 = PyFloat_FromDouble(233.234);
PyObject *fobj_3 = PyNumber_Add(fobj_1, fobj_2);
Py_DECREF(fobj_1);
Py_DECREF(fobj_2);
Py_DECREF(fobj_3);
PyThreadState *ts = PyThreadState_Get();
PyInterpreterState *is = ts->interp;
printf("Free List address: %p\n", is->float_state.free_list);
print_list(is->float_state.free_list, is->float_state.numfree);
Py_Finalize();
return 0;
}
Generally, creating C Extensions, or embedding the interpreter in a C program, does not require the use of such private APIs.
However, if I have such a need, is this approach correct?