Google V8编程详解附录

Google V8编程详工具函数

头文件:utils.h

  1. #ifndef UTILS_H_  
  2. #define UTILS_H_  
  3. #include "v8.h"  
  4. #include <iostream>  
  5. using namespace v8;  
  6. using namespace std;  
  7.   
  8. v8::Handle<v8::String> ReadJS(const char* name);  
  9. void printValue(Handle<Value> result);  
  10. #endif  



  • ReadJS
  1. v8::Handle<v8::String> ReadJS(const char* name) {  
  2.   
  3.         FILE* file = fopen(name, "rb");  
  4.   
  5.         if (file == NULL) {  
  6.                 return v8::Handle<v8::String>();  
  7.         }  
  8.   
  9.         fseek(file, 0, SEEK_END);  
  10.         int size = ftell(file);  
  11.         rewind(file);  
  12.   
  13.         char* chars = new char[size + 1];  
  14.         chars[size] = '';  
  15.   
  16.         for (int i = 0; i < size;) {  
  17.                 int read = fread(&chars[i], 1, size - i, file);  
  18.                 i += read;  
  19.         }  
  20.   
  21.         fclose(file);  
  22.   
  23.         v8::Handle<v8::String> result = v8::String::New(chars, size);  
  24.         delete[] chars;  
  25.         return result;  
  26. }  
  • printValue
[javascript] view plaincopyprint?
 
  1. void printValue(Handle<Value> result) {  
  2.     //感谢downmooner兄的提醒,这个String::Utf8Value str(result)的确让这段代码  
  3.     //南辕北辙  
  4.     //String::Utf8Value str(result);  
  5.   
  6.   
  7.     // just construct the "result" script  
  8.     Handle<Script> script = Script::Compile(String::New("result"));  
  9.     result = script->Run();  
  10.     cout << *String::Utf8Value(result) << endl;  
  11. }  



版权申明:
转载文章请注明原文出处,任何用于商业目的,请联系本人:hyman_tan@126.com

原文地址:https://www.cnblogs.com/MingZznet/p/3231094.html