Associate custom C++ data with a Local<Function> instance

26 views
Skip to first unread message

Darin Dimitrov

unread,
Jun 13, 2019, 5:05:01 AM6/13/19
to v8-users
I am trying to associate some custom C++ data with a Local<Function> instance.

Currently I am able to achieve this only to instances created with this function:

Local<FunctionTemplate> tmpl = FunctionTemplate::New(isolate, [](const FunctionCallbackInfo<Value> &info) {
   
Isolate* isolate = info.GetIsolate();
   
// Associate some custom C++ data with the instance created through this function
    info
.This()->SetInternalField(0, External::New(isolate, nullptr));
});
tmpl
->InstanceTemplate()->SetInternalFieldCount(1);
Local<Function> func = tmpl->GetFunction(context).ToLocalChecked();

Local<Object> instance = func->NewInstance(context).ToLocalChecked();
// Getting back the C++ data associated with the instance
Local<External> extData = instance->GetInternalField(0).As<External>();

What I would like to achieve is to associate the function instance with custom data:

func->SetInternalField(0, External::New(isolate, nullptr));

But unfortunately this throws an "Internal field out of bounds error".

Is it possible to achieve this?

Ben Noordhuis

unread,
Jun 13, 2019, 6:31:24 AM6/13/19
to v8-users
Yes, you can. Put the External on the Function with
Function::SetPrivate(). You can then retrieve it again with
Function::GetPrivate(). Create the Private key with Private::ForApi().

GetPrivate() and SetPrivate() are inherited from Object so it works
for Objects, Arrays, Maps and Sets as well.
Reply all
Reply to author
Forward
0 new messages