[plt-scheme] Re: Finalizer or custodian for extension's resources?
Matthew Flatt wrote:
> For list-related administrative tasks:
> http://list.cs.brown.edu/mailman/listinfo/plt-scheme
>
> At Sun, 13 Jul 2003 20:10:56 +0200, Dirk Gerrits wrote:
>
>>I'm a bit confused on how to tackle resources that need deallocation in
>>MzScheme extensions. I have tried both scheme_register_finalizer on the
>>void* itself, and scheme_add_managed on the object containing the void*
>>but neither does exactly what I want. The former only seems to call the
>>deallocation function on garbage collection of the resource, the latter
>>only when the program ends. But the resource would have to be
>
>
> The intent of the API is that if you want finalization in both cases,
> then you should register both ways (i.e., both the #1 and #2 lines in
> your example).
Thanks for the quick response. I just tried this, but I couldn't get it
to work. With strong=0, the pointer can be garbage collected but the
finalizer isn't called if it happens. With strong=1, the pointer can't
be garbage collected because the custodian is keeping it alive.
What am I doing wrong now?
Dirk Gerrits
Here is the changed code:
void destroy_foo1(void* p, void*)
{
Foo* foo = static_cast<Foo*>(p);
foo->~Foo();
}
void destroy_foo2(Scheme_Object*, void* p)
{
Foo* foo = static_cast<Foo*>(p);
foo->~Foo();
}
Scheme_Object* create_func(int argc, Scheme_Object* argv[])
{
void* foo = scheme_malloc_atomic(sizeof(Foo));
new (foo) Foo;
scheme_register_finalizer(foo, &destroy_foo1, 0, 0, 0);
Scheme_Object* proc = scheme_make_closed_prim_w_arity(
&func,
foo,
"func",
0, 0);
scheme_add_managed(0, proc, &destroy_foo2, foo, 0 /* 1 */);
return proc;
};
For strong=0 I get:
DrScheme: (define func (create-func))
Log after evaluation: Foo()
Log after exit: Foo() ~Foo()
DrScheme: (create-func) (collect-garbage)
Log after evaluation: Foo()
Log after exit: Foo()
For strong=1 I get:
DrScheme: (define func (create-func))
Log after evaluation: Foo()
Log after exit: Foo() ~Foo()
DrScheme: (create-func) (collect-garbage)
Log after evaluation: Foo()
Log after exit: Foo() ~Foo()