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 ...
随机推荐
- mybatis输出SQL
1.导包 下载一个log4j-1.2.17.jar,放到WEB-INF的lib下,并加入build path 2.创建配置文件 在src下创建log4j.properties,填入以下内容: log4 ...
- linux 常用命令学习记录
rm -f *.sh 2.grep -rn "enng" * 查找文件内容包含enng的文件(注意:文件名有xian的不会查询出) find . ! -name "*.s ...
- PLL输出怎么不能配置成我想要的时钟
如下图,我的clk_out7想配置成160M,十几输出变为了150M
- vim 编辑器使用积累(for win)
开个坑,记录一下使用vim的进化历程.这东西不是一两天用的精的,多用自然就觉得有很多地方需要进一步学习,慢慢的效率就上来了. 首先我大部分时间都是在win上做开发,win上的vim需要去自己去配置诸多 ...
- 关于rem的学习
网页常见单位px.em.rem:其中rem是css3新出的单位,官网是这样定义的:“font size of the root element”,意思是:相对长度单位,相对于根元素(即html元素)f ...
- MVC5+EF6 入门完整教程九
前一阵子临时有事,这篇文章发布间隔比较长,我们先回顾下之前的内容,每篇文章用一句话总结重点. 文章一 MVC核心概念简介,一个基本MVC项目结构 文章二 通过开发一个最基本的登录界面,介绍了如何从Co ...
- Windows Store App JavaScript 开发:WinJS库控件
在介绍了如何使用标准的HTML控件以及WinJS库中提供的新控件之后,下面来着重介绍WinJS库中几种常用的控件. (1)ListView控件 在开发Windows应用商店应用时可以使用ListVie ...
- CheckedListBoxControl 实现复选框的单选与多选功能
由于工作需要,需要实现复选框的单选与多选功能,找了好多资料都不是很全,经过两天苦苦的挖挖挖,终于完成啦O(∩_∩)O哈哈~ 用DEV控件中的CheckedListBoxControl控件,当然VS中的 ...
- 使用C++11的一点总结
C++11已不是新鲜技术,但对于我来说,工作中用得还不够多(前东家长时间使用gcc3.4.5,虽然去年升了4.8.2,但旧模块维护还是3.4.5居多:新东家用的是4.4.6,不能完整支持C ...
- Socket通信 简单实现私聊、群聊(dos命令下)
很久以前的一个Demo,这里服务器只做转发功能,根据ID地址和端口号来标识身份,群聊和私聊只是简单实现, 服务器代码如下: import java.util.*; import java.io.*; ...