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 function
Handle<Value> js_result;
// Grab JS function out of file
Handle<v8::Value> value = global->Get(String::New(funcName.c_str()));
// Cast value to v8::Function
Handle<v8::Function> func = v8::Handle<v8::Function>::Cast(value);
// Call function with all set values
js_result = func->Call(global, argCount, argList);
// Return value from function
return js_result;
} int main()
{
//Get the default Isolate
Isolate* isolate = Isolate::GetCurrent(); //Create a stack allocated handle scope
HandleScope handle_scope(isolate); //Handle<Value> init = Integer::New(x); //Create the global template
Handle<ObjectTemplate> global_template = ObjectTemplate::New(); //Create a context
Local<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 ;
} //Compile
Handle<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 arguements
Handle<Value> args[]; // Create arguments to be passed into JS function
AddStringToArguments("BOSS", args, );
AddNumberToArguments(5.0, args, ); // Call the JS function
Handle<Value> js_result = CallJSFunction(global, "JSrepeat", args, );
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 parameters
js_result = CallJSFunction(global, "WhatsMyName", NULL, );
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 program
cout << "\nTest completed. Press enter to exit program. \n" << endl;
std::cin.get(); return ;
} v8::Handle<String> ReadFile(const char* name)
{
//Open the file
FILE* file;
fopen_s(&file, name, "rb"); //If there is no file, return an empty string
if (file == NULL) return v8::Handle<v8::String>(); //Set the pointer to the end of the file
fseek(file, , SEEK_END); //Get the size of file
int size = ftell(file); //Rewind the pointer to the beginning of the stream
rewind(file); //Set up and read into the buffer
char* chars = new char[size + ];
chars[size] = '\0';
for (int i = ; i < size;)
{
int read = static_cast<int>(fread(&chars[i], , 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";
}
C++调用V8与JS交互的更多相关文章
- c#两种方式调用google地球,调用COM API以及调用GEPLUGIN 与js交互,加载kml文件,dae文件。将二维高德地图覆盖到到三维谷歌地球表面。
网络上资源很多不全面,自己在开发的时候走了不少弯路,在这里整理了最全面的google全套开发,COM交互,web端交互.封装好了各种模块功能. 直接就可以调用. 第一种方式:调用COMAPI实现调用g ...
- 关于JS交互--调用h5页面,点击页面的按钮,分享到微信朋友圈,好友
关于js交互,在iOS中自然就想到了调用代理方法 另外就是下面的,直接上代码了: 如果你的后台需要知道你的分享结果,那么,就在回调里面调用上传到服务器结果的请求即可
- UIWebView 与 JS 交互(1):Objective-C 调用 Javascript
众所周知,随着硬件水平的发展,HTML5 与原生 APP 性能差距不断缩小,正在互联网科技领域扮演者越来越重要的角色.作为一种能很大程度上节约成本的技术方案,通过 HTML5 及 JS 实现的跨平台技 ...
- java与js交互,相互调用传参
随着前端技术的发展与H5的广泛使用,移动端采用native+h5的方式越来越多了,对于Android来说就涉及到java与js的交互,相互调用传参等.下面就来看一下java与js交互的简单demo. ...
- iOS JS 交互之利用系统JSContext实现 JS调用OC方法以及Objective-C调用JavaScript方法
ios js 交互分为两块: 1.oc调用js 这一块实现起来比较简单, 我的项目中加载的是本地的html,js,css,需要注意的是当你向工程中拖入这些文件时,选择拷贝到工程中,(拖入的文件夹是蓝色 ...
- iOS JS 交互之利用系统JSContext实现 JS调用oc方法
ios js 交互分为两块: 1.oc调用js 这一块实现起来比较简单, 我的项目中加载的是本地的html,js,css,需要注意的是当你向工程中拖入这些文件时,选择如下操作,(拖入的文件夹是蓝色的, ...
- 【转】第7篇:Xilium CefGlue 关于 CLR Object 与 JS 交互类库封装报告:全自动注册与反射方法分析
作者: 牛A与牛C之间 时间: 2013-12-12 分类: 技术文章 | 2条评论 | 编辑文章 主页 » 技术文章 » 第7篇:Xilium CefGlue 关于 CLR Object 与 JS ...
- CEF和JS交互
CefClient提供所有浏览器事件处理的接口,重写CefClient类中的方法处理浏览器事件:包括Browser的生命周期,右键菜单,对话框,状态通知显示,下载事件,拖曳事件,焦点事件,键盘事件,离 ...
- webView和js交互
与 js 交互 OC 调用 JS // 执行 js - (void)webViewDidFinishLoad:(UIWebView *)webView { NSString *title = [web ...
随机推荐
- jmeter for循环嵌套if学习2
if语句中勾选Evaluate选项,每执行一句都会判断result的值是否为true. 执行结果: three没有执行,到debug时变量的值变成tom了
- 【转】Pycharm的激活
如果要基于Python进行开发的话,那么pycharm是个不错的选择,试用一个月以后需要激活,原文如下: 原文链接:http://blog.csdn.net/lanchunhui/article/de ...
- PHP Switch case 条件并用实例
众所周知,Switch循环比if...else...循环效率要好的多,当case有相同代码结构的时候,怎么样来简化代码结构,能让代码更具有通用性呢? 在网上找了一下,好多都是复制粘贴,还有的看起来太复 ...
- volatile关键字及编译器指令乱序总结
本文简单介绍volatile关键字的使用,进而引出编译期间内存乱序的问题,并介绍了有效防止编译器内存乱序所带来的问题的解决方法,文中简单提了下CPU指令乱序的现象,但并没有深入讨论. 以下是我搭建的博 ...
- gulp教程之gulp-livereload
简介: gulp-livereload拯救F5!当监听文件发生变化时,浏览器自动刷新页面.[事实上也不全是完全刷新,例如修改css的时候,不是整个页面刷新,而是将修改的样式植入浏览器,非常方便.]特别 ...
- php date("Y-m-d H:i:s") 出现警告信息
使用: $createtime=date("Y/m/d H:i:s", time()+16*60*60); $createtime=date("Y-m-d H:i:s&q ...
- 遇到bug怎么办
最近第一个完整的项目的第一期快完成了.期间,我怀疑过无数次人生,给难兄难弟辣椒相互吐槽过.被我师父点播后觉得人和人差距怎么可以这么大数次. 终于!基本功能实现了. 今天不总结具体问题了,说一下调试过程 ...
- UIKit - scrollView缩放、滚动
UIScrollView滚动 三大属性: self.scrollView.pageEnabled = NO 是否分页:n只要将UIScrollView的pageEnabled属性设置为YES,UIS ...
- Singleton Pattern单例模式
单例模式是一种对象创建模式,它用于产生一个对象的具体实例,它可以确保系统中一个类只产生一个实例.Java里面实现的单例是一个虚拟机的范围,因为装载类的功能是虚拟机的,所以一个虚拟机在通过自己的 Cla ...
- ubuntu ulimit 设置
永久设置ubuntu ulimit 之前是ulimit -n 65535那样设置,不过貌似只是当前环境有效果,重启服务器的话,又失效了...今天无意找到一个设置的方法,可以永久设置ulimit的参数. ...