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交互的更多相关文章

  1. c#两种方式调用google地球,调用COM API以及调用GEPLUGIN 与js交互,加载kml文件,dae文件。将二维高德地图覆盖到到三维谷歌地球表面。

    网络上资源很多不全面,自己在开发的时候走了不少弯路,在这里整理了最全面的google全套开发,COM交互,web端交互.封装好了各种模块功能. 直接就可以调用. 第一种方式:调用COMAPI实现调用g ...

  2. 关于JS交互--调用h5页面,点击页面的按钮,分享到微信朋友圈,好友

    关于js交互,在iOS中自然就想到了调用代理方法 另外就是下面的,直接上代码了: 如果你的后台需要知道你的分享结果,那么,就在回调里面调用上传到服务器结果的请求即可

  3. UIWebView 与 JS 交互(1):Objective-C 调用 Javascript

    众所周知,随着硬件水平的发展,HTML5 与原生 APP 性能差距不断缩小,正在互联网科技领域扮演者越来越重要的角色.作为一种能很大程度上节约成本的技术方案,通过 HTML5 及 JS 实现的跨平台技 ...

  4. java与js交互,相互调用传参

    随着前端技术的发展与H5的广泛使用,移动端采用native+h5的方式越来越多了,对于Android来说就涉及到java与js的交互,相互调用传参等.下面就来看一下java与js交互的简单demo. ...

  5. iOS JS 交互之利用系统JSContext实现 JS调用OC方法以及Objective-C调用JavaScript方法

    ios js 交互分为两块: 1.oc调用js 这一块实现起来比较简单, 我的项目中加载的是本地的html,js,css,需要注意的是当你向工程中拖入这些文件时,选择拷贝到工程中,(拖入的文件夹是蓝色 ...

  6. iOS JS 交互之利用系统JSContext实现 JS调用oc方法

    ios js 交互分为两块: 1.oc调用js 这一块实现起来比较简单, 我的项目中加载的是本地的html,js,css,需要注意的是当你向工程中拖入这些文件时,选择如下操作,(拖入的文件夹是蓝色的, ...

  7. 【转】第7篇:Xilium CefGlue 关于 CLR Object 与 JS 交互类库封装报告:全自动注册与反射方法分析

    作者: 牛A与牛C之间 时间: 2013-12-12 分类: 技术文章 | 2条评论 | 编辑文章 主页 » 技术文章 » 第7篇:Xilium CefGlue 关于 CLR Object 与 JS ...

  8. CEF和JS交互

    CefClient提供所有浏览器事件处理的接口,重写CefClient类中的方法处理浏览器事件:包括Browser的生命周期,右键菜单,对话框,状态通知显示,下载事件,拖曳事件,焦点事件,键盘事件,离 ...

  9. webView和js交互

    与 js 交互 OC 调用 JS // 执行 js - (void)webViewDidFinishLoad:(UIWebView *)webView { NSString *title = [web ...

随机推荐

  1. <context:component-scan>使用说明

    Spring组件扫描<context:component-scan/>使用详解 在xml配置了这个标签后,spring可以自动去扫描base-pack下面或者子包下面的java文件,如果扫 ...

  2. Windows Store App 音频和视频

    在Windows应用商店应用中提供了MediaElement控件,该控件能为应用提供音频和视频播放功能.就像之前提到的,虽然在多媒体应用开发中,开发人员可以自行开发一套音频.视频编解码规范和开发媒体播 ...

  3. Swift 04.Functions

    函数的基本构造 基本结构 func 函数名 (形参名:形参类型) ->返回值 {实现代码} 如果没有参数,那么也必须把参数的括号带上 如果有多个形参,那么必须以逗号 , 隔开 如果没有返回值,那 ...

  4. js正则表达式大全(4)

    正则表达式在javascript中的几个实例1(转) ! 去除字符串两端空格的处理 如果采用传统的方式,就要可能就要采用下面的方式了 //清除左边空格 function js_ltrim(destst ...

  5. CSS网页布局全精通

    在本文中将使用四种常见的做法,结合CSS于结构化标记语法制作两栏布局.很快地就会发现,不用嵌套表格,间隔用的GIF也能做出分栏版面布局. 相关文章:CSS网页布局开发小技巧24则 稍后在"技 ...

  6. 高性能 Oracle JDBC 编程

    了解如何利用连接和语句池特性来提高 Oracle 驱动的 JDBC 程序的性能.作者:Yuli Vasiliev2009 年 4 月发布使用诸如连接池和语句池等池技术可以显著提高数据库密集型应用程序的 ...

  7. IE9以下 placeholder兼容

    //input placeholder兼容!(function ($, doc, win) { $.fn.placeholder = function () { var i = doc.createE ...

  8. 【图像处理】【SEED-VPM】1.注意点

    1. 新装系统要启动NFX 每次虚拟机复位要执行以下命令 /usr/sbin/exportfs -av /sbin/service nfs restart —————————————————————— ...

  9. 1171. Lost in Space

    http://acm.timus.ru/problem.aspx?space=1&num=1171 一天的时间,WA了N遍,居然是因为数组开小了呀,我勒个去!鄙视自己...... 我是从第 1 ...

  10. (转)在oracle中varchar和varchar2有什么区别?

    1.varchar2把所有字符都占两字节处理(一般情况下),varchar只对汉字和全角等字符占两字节,数字,英文字符等都是一个字节: 2.VARCHAR2把空串等同于null处理,而varchar仍 ...