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?

Loourr
  • 4,995
  • 10
  • 44
  • 68

1 Answers1

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
}
iefserge
  • 1,136
  • 1
  • 10
  • 10
  • 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. – xaxxon Dec 28 '15 at 03:53
  • 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.) – Shane Lu May 24 '17 at 05:16