forked from Mirror/wren
Get finalizers working.
This commit is contained in:
@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,3 +1,8 @@
|
||||
class Api {
|
||||
foreign static gc()
|
||||
foreign static finalized
|
||||
}
|
||||
|
||||
// Class with a default constructor.
|
||||
foreign class Counter {
|
||||
foreign increment(amount)
|
||||
@ -46,3 +51,25 @@ var error = Fiber.new {
|
||||
class Subclass is Point {}
|
||||
}.try()
|
||||
IO.print(error) // expect: Class 'Subclass' cannot inherit from foreign class 'Point'.
|
||||
|
||||
// Class with a finalizer.
|
||||
foreign class Resource {}
|
||||
|
||||
var resources = [
|
||||
Resource.new(),
|
||||
Resource.new(),
|
||||
Resource.new()
|
||||
]
|
||||
|
||||
Api.gc()
|
||||
IO.print(Api.finalized) // expect: 0
|
||||
|
||||
resources.removeAt(-1)
|
||||
|
||||
Api.gc()
|
||||
IO.print(Api.finalized) // expect: 1
|
||||
|
||||
resources.clear()
|
||||
|
||||
Api.gc()
|
||||
IO.print(Api.finalized) // expect: 3
|
||||
|
||||
Reference in New Issue
Block a user