What is an internal field count and what is SetInternalFieldCount used for?
Asked Answered
T

1

28

I'm having trouble understanding what the SetInternalFieldCount() function actually does. In the v8 documentation the function is described as setting "the number of internal fields for objects generated from this template." Which is pretty self explanatory and unilluminating.

In the v8 embedder's guide they give this example

point_templ->SetInternalFieldCount(1); 

and say "Here the internal field count is set to 1 which means the object has one internal field, with an index of 0, that points to a C++ object."

But what exactly is an internal field and what does setting this value actually tell the program?

Terms answered 17/5, 2013 at 3:2 Comment(0)
T
25

Function SetInternalFieldCount instructs V8 to allocate internal storage slots for every instance created using template. This allowes you store any kind of information inside those instances.

It is useful, for example, to store connection between V8 object and C++ class instance.

void* p;  // any pointer
Local<Object> obj = point_templ->NewInstance();
obj->SetInternalField(0, External::New(p));      // 0 means 1-st internal field

or for aligned pointer:

obj->SetAlignedPointerInInternalField(0, p);     // 0 means 1-st internal field

After this in another part of a program you can get your pointer like this:

v8::Handle<v8::Object> handle;    // some object handle
if (handle->InternalFieldCount() > 0)
{
    void* p = handle->GetAlignedPointerFromInternalField(0); // from 1-st field
    // ... do something with p, e.g. cast it to wrapped C++ class instance
}
Tinea answered 2/9, 2013 at 12:45 Comment(2)
Exactly. This allows some c++ data to tag along with the object so it's available to the object template when it needs to do things like look up or set a value.Brazier
In this case, when the "obj" is GCed in JavaScript, will the object pointed by "p" be deleted as well? (I should have checked the V8 source code first.)Electrum

© 2022 - 2024 — McMap. All rights reserved.