feat: implement foreign object finalization and expose wrenCollectGarbage API

Add finalizer invocation for foreign objects during garbage collection by calling wrenFinalizeForeign in wrenFreeObj. Expose wrenCollectGarbage as a public API function and update internal calls accordingly. Ensure the "<finalize>" symbol is always registered in the symbol table even when no finalizer is provided. Add test fixtures for Resource class with finalizer and Api.gc/Api.finalized methods to verify finalization behavior across multiple GC cycles.
This commit is contained in:
Bob Nystrom
2015-09-01 04:56:21 +00:00
parent 2a8847fa57
commit 4665ec1913
6 changed files with 103 additions and 10 deletions
+31
View File
@@ -3,6 +3,18 @@
#include "foreign_class.h"
static int finalized = 0;
static void apiGC(WrenVM* vm)
{
wrenCollectGarbage(vm);
}
static void apiFinalized(WrenVM* vm)
{
wrenReturnDouble(vm, finalized);
}
static void counterAllocate(WrenVM* vm)
{
double* value = (double*)wrenAllocateForeign(vm, sizeof(double));
@@ -60,8 +72,20 @@ static void pointToString(WrenVM* vm)
wrenReturnString(vm, result, (int)strlen(result));
}
static void resourceAllocate(WrenVM* vm)
{
wrenAllocateForeign(vm, 0);
}
static void resourceFinalize(WrenVM* vm)
{
finalized++;
}
WrenForeignMethodFn foreignClassBindMethod(const char* signature)
{
if (strcmp(signature, "static Api.gc()") == 0) return apiGC;
if (strcmp(signature, "static Api.finalized") == 0) return apiFinalized;
if (strcmp(signature, "Counter.increment(_)") == 0) return counterIncrement;
if (strcmp(signature, "Counter.value") == 0) return counterValue;
if (strcmp(signature, "Point.translate(_,_,_)") == 0) return pointTranslate;
@@ -84,4 +108,11 @@ void foreignClassBindClass(
methods->allocate = pointAllocate;
return;
}
if (strcmp(className, "Resource") == 0)
{
methods->allocate = resourceAllocate;
methods->finalize = resourceFinalize;
return;
}
}