Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 508
Loourr Avatar asked May 17 '13 03:05

Loourr


1 Answers

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
}
like image 133
iefserge Avatar answered Nov 03 '22 09:11

iefserge