C++调用V8与JS交互
C++访问JS函数
C++部分:
/*** COMPILE foo.js AT THE FIRST COMMAND PROMPT TO RUN foo.js*/#include <v8.h> #include <iostream> #include <fstream> #include <string>using namespace v8; using namespace std;v8::Handle<v8::String> ReadFile(const char* name);//******************************* // My helpers //******************************* /** * Add[DataType]ToArguments(string/double/bool, Handle<Value>, UINT) * / [datatype] value to assign to argument list * / pass in arguments handle * / position in argument list to * This function will eaily convert and set the values for an argument list * to easily pass into a JS function you are calling from C++ * JSEx: Func(arg[0], arg[1], ..) **/ void AddStringToArguments(std::string str, Handle<Value> argList[], unsigned int argPos){argList[argPos] = v8::String::New(str.c_str()); } void AddNumberToArguments(double num, Handle<Value> argList[], unsigned int argPos){argList[argPos] = v8::Number::New(num); } void AddBooleanToArguments(bool value, Handle<Value> argList[], unsigned int argPos){argList[argPos] = v8::Boolean::New(value); } // Examples of these pass in the Isolite instead of global and create global within shell.cc for example line 99 /** * CallJSFunction(Handle<v8::Object>, string, Handle<Value>, UINT) * / Handle of the global that is running the script with desired function * / Title of the JS fuction * / List of arguments for function * / Number of agrguments * Returns the return value of the JS function **/ Handle<v8::Value> CallJSFunction(Handle<v8::Object> global, std::string funcName, Handle<Value> argList[], unsigned int argCount){// Create value for the return of the JS functionHandle<Value> js_result;// Grab JS function out of fileHandle<v8::Value> value = global->Get(String::New(funcName.c_str()));// Cast value to v8::FunctionHandle<v8::Function> func = v8::Handle<v8::Function>::Cast(value);// Call function with all set valuesjs_result = func->Call(global, argCount, argList);// Return value from functionreturn js_result; }int main() {//Get the default IsolateIsolate* isolate = Isolate::GetCurrent();//Create a stack allocated handle scope HandleScope handle_scope(isolate);//Handle<Value> init = Integer::New(x);//Create the global templateHandle<ObjectTemplate> global_template = ObjectTemplate::New();//Create a contextLocal<Context> context = Context::New(isolate, NULL, global_template);//Set the context scope Context::Scope context_scope(context);Handle<v8::Object> global = context->Global();string file = "foo.js";while(true){cout << "How many times do you want to run the script? \n" << endl;int n; cin >> n;cout << "" << endl;std::cin.get();Handle<String> source = ReadFile(file.c_str());if(source.IsEmpty()){cout << "Error reading file" << endl;cout << "Press enter to quit" << endl;cin.get();return 0;}//CompileHandle<Script> script = Script::Compile(source);//Run the script and print Handle<Value> result;result = script->Run();// Once script has ran lets call some Functions!!******************// Create handle for arguementsHandle<Value> args[2];// Create arguments to be passed into JS functionAddStringToArguments("BOSS", args, 0);AddNumberToArguments(5.0, args, 1);// Call the JS functionHandle<Value> js_result = CallJSFunction(global, "JSrepeat", args, 2);String::AsciiValue ascii2(js_result);printf("JSrepeat() returned: %s\n", ascii2);// Lets try another JS fucntion call!!*****************************// This function returns the name "Jimmy" with no parametersjs_result = CallJSFunction(global, "WhatsMyName", NULL, 0);String::AsciiValue ascii3(js_result);printf("WhatsMyName() returned: %s\n", ascii3);String::AsciiValue ascii(result);cout << "Script result : " ;printf("%s\n", *ascii);} // End of while//Exit programcout << "\nTest completed. Press enter to exit program. \n" << endl;std::cin.get();return 0; }v8::Handle<String> ReadFile(const char* name) {//Open the fileFILE* file;fopen_s(&file, name, "rb");//If there is no file, return an empty stringif (file == NULL) return v8::Handle<v8::String>();//Set the pointer to the end of the filefseek(file, 0, SEEK_END);//Get the size of fileint size = ftell(file);//Rewind the pointer to the beginning of the stream rewind(file);//Set up and read into the bufferchar* chars = new char[size + 1];chars[size] = '\0';for (int i = 0 ; i < size;){int read = static_cast<int>(fread(&chars[i], 1, size - i, file));i += read;}//Close file fclose(file);v8::Handle<v8::String> result = v8::String::New(chars, size);delete[] chars;return result; }
JS部分:
function test_function() { var match = 0;if(arguments[0] == arguments[1]) { match = 1; } return match; }function JSrepeat(name, repeat) { var printthis = "";for(var i=0; i < repeat; i++){printthis += name;}return printthis; }function ReturnThis(anything) { return anything; }function WhatsMyName() { return "Jimmy"; }
转载于:https://www.cnblogs.com/iRoad/p/4133490.html
C++调用V8与JS交互相关推荐
- winform利用CefSharp调用google浏览器内核ChromiumWebBrowser,与JS交互
一开始用了自带的webbrowser,不支持H5,脚本会有问题,后来又用了webkitBrowser,发现有些js效果还是显示不出来,和webbrowser稍微好一点,但是还是不行,然后决定用CefS ...
- java与js交互,相互调用传参
随着前端技术的发展与H5的广泛使用,移动端采用native+h5的方式越来越多了,对于Android来说就涉及到java与js的交互,相互调用传参等.下面就来看一下java与js交互的简单demo. ...
- python调用远程js_python和js交互调用的方法
后台代码都是利用的1.[get方式]使用jquery的get json与后台交互前端js代码片段var data= {'a': $('input[name="a"]').val() ...
- python中和js交互_python和js交互调用的方法
后台代码都是利用的 1.[get方式]使用jquery的get json与后台交互 前端js代码片段 var data= { 'a': $('input[name="a"]').v ...
- C#winForm程序与html JS交互调用
程序是这样的,在winForm里拖了一个webBrowser 如图,一大片空白: 然后这个winForm界面的代码: 1.注意这个类的头部必须加上以下代码: [System.Runtime.Inte ...
- 【转】第7篇:Xilium CefGlue 关于 CLR Object 与 JS 交互类库封装报告:全自动注册与反射方法分析...
作者: 牛A与牛C之间 时间: 2013-12-12 分类: 技术文章 | 2条评论 | 编辑文章 主页 » 技术文章 » 第7篇:Xilium CefGlue 关于 CLR Object 与 JS ...
- 浏览器原理-v8引擎-js执行原理
浏览器原理-v8引擎-js执行原理 js简介 js应用: js的应用很广泛 可以应用于web,移动端,小程序,桌面应用,后端开发等 web开发包括(原生js,react,vue,angular等) 移 ...
- iOS与JS交互的4种方法
iOS与JS交互的方法: 1.拦截url(适用于UIWebView和WKWebView) 2.JavaScriptCore(只适用于UIWebView,iOS7+) 3.WKScriptMessage ...
- 客户端C++与前端js交互
客户端与前端交互 qwebchannel.js文件引入 建立通信 // c++发送消息给js new QWebChannel(qt.webChannelTransport, function(chan ...
- (0085)iOS开发之OC与JS交互高级用法(JavaScriptCore)
前述:JavaScriptCore你不知道的OC与JS之间交互.OC与JS之间用model实现交互.通讯.传值!好玩! 几乎三年来一直断断续续接触OC与JS交互,每次觉得UIWebView OC与JS ...
最新文章
- 22.调用delay()方法延时执行动画效果
- 三国志幻想大陆服务器维护,三国志幻想大陆8月14日更新维护公告
- Linux and the Device Tree
- c语言矩阵存储,C语言实现特殊矩阵存储
- 2015 10月21日 工作计划与执行
- 计算机二级考试c语言冲刺,计算机二级C语言考试冲刺练习题
- uc for linux,在uClinux文件系统中增加应用程序
- BZOJ1123: [POI2008]BLO
- Java基础———第一弹
- 2018年面试题大全
- 图片实现裁剪功能vue-img-cutter
- 安利一款免费、开源、实时的服务器监控工具:Netdata
- 大学计算机基础模拟系统2014ppt第三,第一章_河海大学:大学计算机信息技术_ppt_大学课件预览_高等教育资讯网...
- UEA数据集和UCR数据集的处理
- Python 处理日期与时间的全面总结!
- 什么是async/await?
- php985工程,985大学名单排名最新
- 互联网运营面试题_网站运营面试问题
- 隔得时间长不用小程序原生要注意的点
- shell脚本(一)批量修改图片名称