google v8使用示例

概念解释
Handle
V8里使用Handle类型来托管 JavaScript对象,与C++的std::shared_pointer类似,Handle类型间的赋值均是直接传递对象引用,但不同的是,V8使用自己的GC来管理对象生命周期,而不是智能指针常用的引用计数。如果一个v8对象没有任何Handle与之相关联(不再被访问),那么这个对象很快就会被垃圾回收器回收掉。
Handle有两种类型,Local Handle和Persistent Handle,类型分别是Local : Handle和Persistent : Handle,前者和Handle没有区别,生存周期都在scope内。而后者的生命周期脱离scope,你需要手动调用Persistent::Dispose结束其生命周期。也就是说Local Handle相当于在C++在栈上分配对象,而Persistent Handle相当于C++在堆上分配对象。
 
Isolate
Isolate表示一个独立的v8引擎实例,每个实例维护不同的状态。一个Isolate中的对象不能在其他Isolate中使用。当v8被初始化的时候,一个默认isolate被默认创建。开发者可以通过创建额外的Isolate在多线程环境下并行使用。一个Isolate任意时间只允许一个线程在其中运行,可以使用Locker和Unlocker来进行多个线程对一个Isolate的同步。

Context
V8允许不同的JavaScript代码运行在完全不同的环境下,其运行环境称为Context。不同的Context下拥有自己的全局对象(PersistentHandle),运行代码时必须指定所在的Context。最典型的例子就是Chrome的标签,每个标签都拥有自己的Context。
Context拥有自己的全局代理对象(global proxy object),每个Context下的全局对象都是这个全局代理对象的属性。通过Context::Global ()可以得到这个全局代理对象。新建Context时你可以手动指定它的全局代理对象,这样每个Context都会自动拥有一些全局对象,比如DOM。
Context也是一种scope,通过Context::Enter ()和Context::Exit ()来进入、退出,或者使用类似于HandleScope的Context::Scope来隐式进入。

External
v8::External,它的作用是把C++的对象包装成Javascript中的变量。External::New接受一个C++对象的指针作为初始化参数,然后返回一个包含这个指针的Handle对象供v8引擎使用。在使用这个Handle对象时可以通过External::Value函数来得到C++对象的指针。

Template
Template是介于Javascript和C++变量间的中间层,你首先由C++对象生成一个Template,然后再由Template生成Javascript函数的对象。你可以事先在Template中准备好一些预备属性,然后生成的Javascript对象都将具备这些属性。
 
FunctionTemplate
你可以使用FunctionTemplate::New ()生成一个空函数,然后用FunctionTemplate::SetCallHandler ()将其和C++函数绑定,或者直接靠FunctionTemplate::New (InvocationCallback callback)来用C++函数初始化一个FunctionTemplate。
用来生成FunctionTemplate的C++函数必须满足InvocationCallback的条件,即函数签名必须如下:
  1. typedef Handle<Value> (*InvocationCallback)(const Arguments& args);
如果是简单给js脚本使用,创建并设置完FunctionTemplate就可以了;但是如果在c++中使用FunctionTemplate或者是需要为Function设置一些属性字段的话,需要从FunctionTemplate通过GetFunction()来创建一个Function。
此后,你可以使用FunctionTemplate::GetFunction()来获取对应的v8::Function。但是一个FunctionTemplate只能生成一个Function,FunctionTemplate::GetFunction()返回的都是同一个实体。这是因为Javascript里显式声明的全局函数只有一个实例。
Javascript常用new Function ();的形式来创建对象,而C++中,Function::NewInstance可以返回一个函数的Instance。你可以使用Function::NewInstance返回一个函数对象,等同于Javascript中的var tmp = new func;。

ObjectTemplate
ObjectTemplate的目的就是根据包装起来的C++对象生成v8::Object。接口与Template也大致相当,通过ObjectTemplate::New返回新的ObjectTemplate,通过ObjectTemplate::NewInstance。ObjectTemplate提供了一种Internal Field,也就是内部储存空间,我们可以通过External类型把C++对象储存在ObjectTemplate中。
建立了ObjectTemplate后,我们可以通过ObjectTemplate::SetInternalFieldCount设定内部储存多少个内部变量。然后通过ObjectTemplate::NewInstance建立新的Object,再在v8::Object中通过SetInternalField来对内部变量进行操作。
Accessors的实现原理就是为Object绑定一个C++对象,并为其在全局代理对象中设置一个名字,当JavaScript按指定的名字访问Object的时候,调用Getter和Setter函数来访问C++对象数据。
 
>>> 如果需要在Function中创建一个Function,处理一个C++对象。首先需要将这个C++对象使用SetInnerField封转到一个Object中;其次在FunctionTemplate::New的时候,将Object作为data参数传入New函数,这样在创建的Function中就可以通过args.Data()获取到之前的Object了(Value类型的,使用ToObject转成Object类型),然后通过GetPointerFromInnerField就可以获得之前的C++对象了。

示例代码
直接上代码
  1. #include <string>
  2. #include <cstring>

  3. #include <sys/time.h>

  4. #include <v8.h>

  5. using namespace v8;

  6. #ifndef THREAD_NUM
  7. #define THREAD_NUM 4
  8. #endif

  9. #ifndef DEF_CALLS
  10. #define DEF_CALLS 100000
  11. #endif

  12. #ifdef NO_LOG

  13. #define CDEBUG_LOG(format, args...) 
  14. #define CTRACE_LOG(format, args...) 
  15. #define CWARNING_LOG(format, args...) 
  16. #define CFATAL_LOG(format, args...) 

  17. #else

  18. #define CDEBUG_LOG(format, args...) \
  19.     do{\
  20.          char tmpstr[65536];\
  21.          snprintf(tmpstr,65535,format,##args);\
  22.          printf("[thread:%u] %s\n", pthread_self(), tmpstr); \
  23.     }while(0)
  24. #define CTRACE_LOG(format, args...) \
  25.     do{\
  26.          char tmpstr[65536];\
  27.          snprintf(tmpstr,65535,format,##args);\
  28.          printf("[thread:%u] %s\n", pthread_self(), tmpstr); \
  29.     }while(0)
  30. #define CWARNING_LOG(format, args...) \
  31.     do{\
  32.          char tmpstr[65536];\
  33.          snprintf(tmpstr,65535,format,##args);\
  34.          printf("[thread:%u] %s\n", pthread_self(), tmpstr); \
  35.     }while(0)
  36. #define CFATAL_LOG(format, args...) \
  37.     do{\
  38.          char tmpstr[65536];\
  39.          snprintf(tmpstr,65535,format,##args);\
  40.          printf("[thread:%u] %s\n", pthread_self(), tmpstr); \
  41.     }while(0)

  42. #endif

  43. static Handle<Value> IntGetter(Local<String>name, const AccessorInfo &info)
  44. {
  45.     String::Utf8Value utf8_value_name(name);
  46.     std::string key(*utf8_value_name);
  47.     const char * strKey = key.c_str();

  48.     if(strcmp(strKey, "c"))
  49.     {
  50.         return Int32::New(3);
  51.     }
  52.     else if(strcmp(strKey, "d"))
  53.     {
  54.         return Int32::New(4);
  55.     }

  56.     return Int32::New(1);
  57. }

  58. static Handle<Value> NamedGetter(Local<String>name, const AccessorInfo &info)
  59. {
  60.     String::Utf8Value utf8_value_name(name);
  61.     std::string key(*utf8_value_name);
  62.     const char * strKey = key.c_str();

  63.     if(strcmp(strKey, "f1"))
  64.     {
  65.         return Int32::New(5);
  66.     }
  67.     else if(strcmp(strKey, "f2"))
  68.     {
  69.         return Int32::New(6);
  70.     }

  71.     return Int32::New(1);
  72. }

  73. static Handle<Value> IndexedGetter(uint32_t index, const AccessorInfo &info)
  74. {
  75.     if(index==1)
  76.         return Int32::New(7);
  77.     else if(index==2)
  78.         return Int32::New(8);

  79.     return Int32::New(1);
  80. }

  81. static Handle<Value> Sum(const Arguments &args)
  82. {
  83.     if(args.Length()!=2)
  84.         return Undefined();
  85.     if(args[0]->IsInt32() && args[1]->IsInt32())
  86.         return Int32::New(args[0]->Int32Value()+args[1]->Int32Value());
  87.     else
  88.         return Undefined();
  89. }

  90. void *v8_func_op(void *)
  91. {
  92.     int count = 0;
  93.     struct timeval tvStart;
  94.     struct timeval tvEnd;
  95.     // Create a stack-allocated handle scope.
  96.     HandleScope handle_scope;

  97.     // Create a ObjectTemplate
  98.     Handle<ObjectTemplate> global = ObjectTemplate::New();
  99.     //Function Set before Context::New
  100.     global->Set(String::New("Sum"), FunctionTemplate::New(Sum));

  101.     Persistent<Context> context = Context::New(NULL, global);
  102.     // Create a new context.
  103.     //Persistent<Context> context = Context::New();
  104.     Context::Scope context_scope(context);

  105.     //Sum(1,2);
  106.     //*
  107.     (void) gettimeofday(&tvStart, NULL);
  108.     for(int i=0; i<DEF_CALLS; i++)
  109.     {
  110.         // Create a stack-allocated handle scope.
  111.         HandleScope handle_subscope;

  112.         const char *JS_STR = "Sum(1,1)";
  113.         Handle<String> source = String::New( JS_STR );
  114.         Handle<Script> script = Script::Compile(source);

  115.         // Run the script to get the result.
  116.         TryCatch trycatch;
  117.         Handle<Value> result = script->Run();
  118.         if(result.IsEmpty())
  119.         {
  120.             Handle<Value> exception = trycatch.Exception();
  121.             String::AsciiValue exception_str(exception);
  122.             printf("Exception: %s\n", *exception_str);
  123.         }
  124.         else
  125.         {
  126.             if(result->IsInt32())
  127.             {
  128.                 CDEBUG_LOG("JS RET: %d", result->Int32Value());
  129.             }
  130.             else
  131.             {
  132.                 CDEBUG_LOG("JS FAILED");
  133.             }
  134.         }
  135.     }
  136.     (void) gettimeofday(&tvEnd, NULL);
  137.     fprintf(stdout, "[thread:%u] %u calls - timespan : %lu us\n", pthread_self(), DEF_CALLS, (tvEnd.tv_sec-tvStart.tv_sec)*1000000+(tvEnd.tv_usec-tvStart.tv_usec));
  138.     usleep(2000);
  139.     //*/
  140.     
  141.     //1+1==2
  142.     //*
  143.     (void) gettimeofday(&tvStart, NULL);
  144.     for(int i=0; i<DEF_CALLS; i++)
  145.     {
  146.         // Create a stack-allocated handle scope.
  147.         HandleScope handle_subscope;

  148.         const char *JS_STR = "1+1==2";
  149.         Handle<String> source = String::New( JS_STR );
  150.         Handle<Script> script = Script::Compile(source);

  151.         // Run the script to get the result.
  152.         TryCatch trycatch;
  153.         Handle<Value> result = script->Run();
  154.         if(result.IsEmpty())
  155.         {
  156.             Handle<Value> exception = trycatch.Exception();
  157.             String::AsciiValue exception_str(exception);
  158.             printf("Exception: %s\n", *exception_str);
  159.         }
  160.         else
  161.         {
  162.             if(result->IsBoolean())
  163.             {
  164.                 if(result->BooleanValue())
  165.                 {
  166.                     CDEBUG_LOG("JS RET: TRUE");
  167.                 }
  168.                 else
  169.                 {
  170.                     CDEBUG_LOG("JS RET: FALSE");
  171.                 }
  172.             }
  173.             else
  174.             {
  175.                 CDEBUG_LOG("JS FAILED");
  176.             }
  177.         }
  178.     }
  179.     (void) gettimeofday(&tvEnd, NULL);
  180.     fprintf(stdout, "[thread:%u] %u calls - timespan : %lu us\n", pthread_self(), DEF_CALLS, (tvEnd.tv_sec-tvStart.tv_sec)*1000000+(tvEnd.tv_usec-tvStart.tv_usec));
  181.     usleep(2000);
  182.     //*/

  183.     //static set: a+b
  184.     //*
  185.     context->Global()->Set(String::New("a"), Int32::New(1));
  186.     context->Global()->Set(String::New("b"), Int32::New(2));

  187.     (void) gettimeofday(&tvStart, NULL);
  188.     for(int i=0; i<DEF_CALLS; i++)
  189.     {
  190.         // Create a stack-allocated handle scope.
  191.         HandleScope handle_subscope;

  192.         const char *JS_STR = "a+b";
  193.         Handle<String> source = String::New( JS_STR );
  194.         Handle<Script> script = Script::Compile(source);

  195.         // Run the script to get the result.
  196.         TryCatch trycatch;
  197.         Handle<Value> result = script->Run();
  198.         if(result.IsEmpty())
  199.         {
  200.             Handle<Value> exception = trycatch.Exception();
  201.             String::AsciiValue exception_str(exception);
  202.             printf("Exception: %s\n", *exception_str);
  203.         }
  204.         else
  205.         {
  206.             if(result->IsInt32())
  207.             {
  208.                 CDEBUG_LOG("JS RET: %d", result->Int32Value());
  209.             }
  210.             else
  211.             {
  212.                 CDEBUG_LOG("JS FAILED");
  213.             }
  214.         }
  215.     }
  216.     (void) gettimeofday(&tvEnd, NULL);
  217.     fprintf(stdout, "[thread:%u] %u calls - timespan : %lu us\n", pthread_self(), DEF_CALLS, (tvEnd.tv_sec-tvStart.tv_sec)*1000000+(tvEnd.tv_usec-tvStart.tv_usec));
  218.     usleep(2000);
  219.     //*/

  220.     //static accessor: c+d
  221.     //*
  222.     context->Global()->SetAccessor(String::New("c"), IntGetter);
  223.     context->Global()->SetAccessor(String::New("d"), IntGetter);

  224.     (void) gettimeofday(&tvStart, NULL);
  225.     for(int i=0; i<DEF_CALLS; i++)
  226.     {
  227.         // Create a stack-allocated handle scope.
  228.         HandleScope handle_subscope;

  229.         const char *JS_STR = "c+d";
  230.         Handle<String> source = String::New( JS_STR );
  231.         Handle<Script> script = Script::Compile(source);

  232.         // Run the script to get the result.
  233.         TryCatch trycatch;
  234.         Handle<Value> result = script->Run();
  235.         if(result.IsEmpty())
  236.         {
  237.             Handle<Value> exception = trycatch.Exception();
  238.             String::AsciiValue exception_str(exception);
  239.             printf("Exception: %s\n", *exception_str);
  240.         }
  241.         else
  242.         {
  243.             if(result->IsInt32())
  244.             {
  245.                 CDEBUG_LOG("JS RET: %d", result->Int32Value());
  246.             }
  247.             else
  248.             {
  249.                 CDEBUG_LOG("JS FAILED");
  250.             }
  251.         }
  252.     }
  253.     (void) gettimeofday(&tvEnd, NULL);
  254.     fprintf(stdout, "[thread:%u] %u calls - timespan : %lu us\n", pthread_self(), DEF_CALLS, (tvEnd.tv_sec-tvStart.tv_sec)*1000000+(tvEnd.tv_usec-tvStart.tv_usec));
  255.     usleep(2000);
  256.     //*/

  257.     //named property: e.f1+e.f2
  258.     //*
  259.     Handle<ObjectTemplate> named = ObjectTemplate::New();
  260.     named->SetNamedPropertyHandler(NamedGetter, NULL);
  261.     context->Global()->Set(String::New("e"), named->NewInstance());

  262.     (void) gettimeofday(&tvStart, NULL);
  263.     for(int i=0; i<DEF_CALLS; i++)
  264.     {
  265.         // Create a stack-allocated handle scope.
  266.         HandleScope handle_subscope;

  267.         const char *JS_STR = "e.f1+e.f2";
  268.         Handle<String> source = String::New( JS_STR );
  269.         Handle<Script> script = Script::Compile(source);

  270.         // Run the script to get the result.
  271.         TryCatch trycatch;
  272.         Handle<Value> result = script->Run();
  273.         if(result.IsEmpty())
  274.         {
  275.             Handle<Value> exception = trycatch.Exception();
  276.             String::AsciiValue exception_str(exception);
  277.             printf("Exception: %s\n", *exception_str);
  278.         }
  279.         else
  280.         {
  281.             if(result->IsInt32())
  282.             {
  283.                 CDEBUG_LOG("JS RET: %d", result->Int32Value());
  284.             }
  285.             else
  286.             {
  287.                 CDEBUG_LOG("JS FAILED");
  288.             }
  289.         }
  290.     }
  291.     (void) gettimeofday(&tvEnd, NULL);
  292.     fprintf(stdout, "[thread:%u] %u calls - timespan : %lu us\n", pthread_self(), DEF_CALLS, (tvEnd.tv_sec-tvStart.tv_sec)*1000000+(tvEnd.tv_usec-tvStart.tv_usec));
  293.     usleep(2000);
  294.     //*/
  295.     
  296.     //indexed property: f[1]+f[2]
  297.     //*
  298.     Handle<ObjectTemplate> indexed = ObjectTemplate::New();
  299.     indexed->SetIndexedPropertyHandler(IndexedGetter, NULL);
  300.     context->Global()->Set(String::New("f"), indexed->NewInstance());

  301.     (void) gettimeofday(&tvStart, NULL);
  302.     for(int i=0; i<DEF_CALLS; i++)
  303.     {
  304.         // Create a stack-allocated handle scope.
  305.         HandleScope handle_subscope;

  306.         const char *JS_STR = "f[1]+f[2]";
  307.         Handle<String> source = String::New( JS_STR );
  308.         Handle<Script> script = Script::Compile(source);

  309.         // Run the script to get the result.
  310.         TryCatch trycatch;
  311.         Handle<Value> result = script->Run();
  312.         if(result.IsEmpty())
  313.         {
  314.             Handle<Value> exception = trycatch.Exception();
  315.             String::AsciiValue exception_str(exception);
  316.             printf("Exception: %s\n", *exception_str);
  317.         }
  318.         else
  319.         {
  320.             if(result->IsInt32())
  321.             {
  322.                 CDEBUG_LOG("JS RET: %d", result->Int32Value());
  323.             }
  324.             else
  325.             {
  326.                 CDEBUG_LOG("JS FAILED");
  327.             }
  328.         }
  329.     }
  330.     (void) gettimeofday(&tvEnd, NULL);
  331.     fprintf(stdout, "[thread:%u] %u calls - timespan : %lu us\n", pthread_self(), DEF_CALLS, (tvEnd.tv_sec-tvStart.tv_sec)*1000000+(tvEnd.tv_usec-tvStart.tv_usec));
  332.     usleep(2000);
  333.     //*/
  334.     
  335.     //Should Call GC
  336.     V8::IdleNotification();
  337.     V8::LowMemoryNotification();
  338.     V8::ContextDisposedNotification();

  339.     //Heap Statis
  340.     {
  341.         HeapStatistics hs;
  342.         V8::GetHeapStatistics(&hs);
  343.         fprintf(stderr, "[thread:%u] "
  344.                 "total_heap_size:%u "
  345.                 "total_heap_size_executable:%u "
  346.                 "used_heap_size:%u "
  347.                 "heap_size_limit:%u\n",
  348.                 pthread_self(),
  349.                 hs.total_heap_size(),
  350.                 hs.total_heap_size_executable(),
  351.                 hs.used_heap_size(),
  352.                 hs.heap_size_limit());
  353.     }

  354.     // Dispose the persistent context.
  355.     context.Dispose();
  356.     context.Clear();

  357.     //return 0;
  358.     return NULL;
  359. }

  360. void * v8_func(void *)
  361. {
  362.     //One thread have an isolate
  363.     v8::Isolate* isolate = v8::Isolate::New();
  364.     {
  365.         Locker locker(isolate);
  366.         v8::Isolate::Scope iscope(isolate);

  367.         //*
  368.         {
  369.             ResourceConstraints rc;
  370.             rc.set_max_young_space_size(2048); //KB
  371.             rc.set_max_old_space_size(10); //MB
  372.             rc.set_max_executable_size(10); //MB
  373.             rc.set_stack_limit(reinterpret_cast<uint32_t*>((char*)&rc- 1024 * 400));

  374.             SetResourceConstraints(&rc);
  375.         }
  376.         //*/

  377.         v8_func_op(NULL);
  378.     }

  379.     isolate->Dispose();

  380.     return NULL;
  381. }

  382. int main(int argc, char *argv[])
  383. {
  384. #define MAX_THREAD_NUM 120
  385.     pthread_t pid[MAX_THREAD_NUM] = {0};
  386.     void * res = NULL;
  387.     int thread_num = THREAD_NUM;

  388.     V8::SetFlagsFromCommandLine(&argc, argv, true); 

  389.     for(int i=0; i<thread_num; i++)
  390.         pthread_create(&pid[i], NULL, v8_func, NULL);

  391.     for(int i=0; i<thread_num; i++)
  392.         pthread_join(pid[i], &res);

  393.     return 0;
  394. }

参考
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值