This commit is contained in:
blueloveTH 2025-10-20 17:52:42 +08:00
parent e39e63191f
commit 7efcbb136e
4 changed files with 28 additions and 2 deletions

View File

@ -78,6 +78,7 @@ typedef struct VM {
void VM__ctor(VM* self);
void VM__dtor(VM* self);
int VM__index(VM* self);
void VM__push_frame(VM* self, py_Frame* frame);
void VM__pop_frame(VM* self);

View File

@ -90,6 +90,12 @@ typedef struct py_Callbacks {
void (*gc_mark)(void (*f)(py_Ref val, void* ctx), void* ctx);
} py_Callbacks;
/// A struct contains the application-level callbacks.
typedef struct py_AppCallbacks {
void (*on_vm_ctor)(int index);
void (*on_vm_dtor)(int index);
} py_AppCallbacks;
/// Native function signature.
/// @param argc number of arguments.
/// @param argv array of arguments. Use `py_arg(i)` macro to get the i-th argument.
@ -125,6 +131,8 @@ PK_API void* py_getvmctx();
PK_API void py_setvmctx(void* ctx);
/// Setup the callbacks for the current VM.
PK_API py_Callbacks* py_callbacks();
/// Setup the application callbacks
PK_API py_AppCallbacks* py_appcallbacks();
/// Set `sys.argv`. Used for storing command-line arguments.
PK_API void py_sys_setargv(int argc, char** argv);

View File

@ -278,9 +278,19 @@ void VM__ctor(VM* self) {
} while(0);
self->main = py_newmodule("__main__");
if(py_appcallbacks()->on_vm_ctor) {
int index = VM__index(self);
py_appcallbacks()->on_vm_ctor(index);
}
}
void VM__dtor(VM* self) {
if(py_appcallbacks()->on_vm_dtor) {
int index = VM__index(self);
py_appcallbacks()->on_vm_dtor(index);
}
// reset traceinfo
py_sys_settrace(NULL, true);
LineProfiler__dtor(&self->line_profiler);

View File

@ -65,13 +65,15 @@ void py_finalize() {
pk_names_finalize();
}
int py_currentvm() {
int VM__index(VM* self) {
for(int i = 0; i < 16; i++) {
if(pk_all_vm[i] == pk_current_vm) return i;
if(pk_all_vm[i] == self) return i;
}
return -1;
}
int py_currentvm() { return VM__index(pk_current_vm); }
void py_switchvm(int index) {
if(index < 0 || index >= 16) c11__abort("invalid vm index");
if(!pk_all_vm[index]) {
@ -104,6 +106,11 @@ void py_setvmctx(void* ctx) { pk_current_vm->ctx = ctx; }
py_Callbacks* py_callbacks() { return &pk_current_vm->callbacks; }
py_AppCallbacks* py_appcallbacks() {
static py_AppCallbacks _callbacks = {0};
return &_callbacks;
}
/////////////////////////////
void py_sys_setargv(int argc, char** argv) {