I'm using FunctionTemplate to create a function that has callback data, and 
I want to get a callback when the function is no longer reachable from 
Javascript so I can do some cleanup associated with the callback data. I'm 
trying to do this with a weak reference callback, but I'm having some 
trouble getting the weak callback to actually get called.

MVCE:

#include <stdlib.h>
#include <stdio.h>
#include <v8.h>
#include <libplatform/libplatform.h>

using namespace v8;

class MallocAllocator : public ArrayBuffer::Allocator {
    public:
    virtual void *Allocate(size_t size) {
        void *data = AllocateUninitialized(size);
        if (data != NULL)
            memset(data, 0, size);
        return data;
    }
    virtual void *AllocateUninitialized(size_t size) {
        return malloc(size);
    }
    virtual void Free(void *data, size_t size) {
        free(data);
    }
};

void func_callback(const FunctionCallbackInfo<Value> &info) {}

void weak_callback(const WeakCallbackInfo<Persistent<String>> &info) {
    Persistent<String> *handle = info.GetParameter();
    printf("weak callback called with %p\n", handle);
    delete handle;
}

int main() {
    V8::InitializeICU();
    Platform *current_platform = platform::CreateDefaultPlatform();
    V8::InitializePlatform(current_platform);
    V8::Initialize();
    V8::SetFlagsFromString("--expose_gc", strlen("--expose_gc"));
    Isolate::CreateParams params;
    params.array_buffer_allocator = new MallocAllocator();
    Isolate *isolate = Isolate::New(params);
    HandleScope hs(isolate);

    Local<Context> context = Context::New(isolate);
    Local<String> key = String::NewFromUtf8(isolate, "test", NewStringType::
kNormal).ToLocalChecked();

    Persistent<String> *weak_str = new Persistent<String>();
    {
        HandleScope hs(isolate);
        Local<String> str = String::NewFromUtf8(isolate, "hi there", 
NewStringType::kNormal).ToLocalChecked();

        Local<FunctionTemplate> templ = FunctionTemplate::New(isolate, 
func_callback, str);

        weak_str->Reset(isolate, str);
        weak_str->SetWeak(weak_str, weak_callback, WeakCallbackType::
kParameter);
        context->Global()->Set(context,
                key, templ->GetFunction(context).ToLocalChecked())
            .FromJust();
    }

    context->Global()->Delete(context, key).FromJust();

    isolate->RequestGarbageCollectionForTesting(Isolate::
GarbageCollectionType::kFullGarbageCollection);
    return 0;
}

In this program, weak_callback never gets called. Anyone know why?

Thanks,
~Theodore

-- 
-- 
v8-users mailing list
[email protected]
http://groups.google.com/group/v8-users
--- 
You received this message because you are subscribed to the Google Groups 
"v8-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
For more options, visit https://groups.google.com/d/optout.

Reply via email to