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 ...
随机推荐
- JAVA方法03之动手动脑问题解决
动手动脑1.当JAVA里定义的函数中去掉static后,怎么办?(如下程序,将square()函数的static去掉) public class SquareIntTest { public stat ...
- C++内存管理的缩影
都说C++内存管理是个大坑.实际上也确实是这样. C++有析构函数,每当一个对象过期的时候,C++会执行两个动作 1.执行析构函数. 2.将对象和对象的所有数据删除. 很多人就会问了,既然有把对象删除 ...
- About “this” of Javascript
the 4 point about This: 1.the use of Object methods 2.the use of constructors 3.the use of ordinary ...
- HEAD FIRST HTML & CSS学习笔记1
一.指定媒体类型=指定显示设备的类型 P400 有两种方式指定媒体类型: a. 直接在<link>标签中加属性media,例: <link href="print.css ...
- EasyUI相关
失去焦点事件 validType:'length[4,15]',events:{blur: function(){}} 添加自定义属性 $.extend($.fn.validatebox.defaul ...
- PHPCMS开启伪静态和织梦开启伪静态的优缺点比较
PHPCMS和织梦CMS都是国内比较出名的PHP语言的CMS程序系统,他们拥有比较完善的网站内容管理功能,也比较注重网站优化方面的功能,深受很多网站建设者的喜爱. 这两套系统,都有启用伪静态的功能,在 ...
- 小游戏Item表
[Config]1|0|我|1|10|500|0|8|2|4|b5222d10-55a7-4789-8541-8e7430345d54|0|0[Config] [Config]2|1|公主|1|0|5 ...
- Java 入门(一) - 环境变量
Win 7 X64环境 计算机(右键)-> 属性 -> 高级系统设置 -> 环境变量1.新建系统变量 : JAVA_HOME C:\Program Files (x86)\Java\ ...
- iOS语音
<span style="white-space:pre"> </span>语音技术近来可是出遍了风头,从iphone4s的siri,到微信的语音聊天 ...
- 洛谷 1004 dp或最大费用流
思路: dp方法: 设dp[i][j][k][l]为两条没有交叉的路径分别走到(i,j)和(k,l)处最大价值. 则转移方程为 dp[i][j][k][l]=max(dp[i-1][j][k-1][l ...