Google V8 编程入门(二) - 使用c++访问js脚本对象

// v8test.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <v8.h>
#pragma comment(lib, "v8_base.lib")
#pragma comment(lib, "v8_snapshot.lib")
#pragma comment(lib, "ws2_32.lib")
#pragma comment(lib, "winmm.lib")

using namespace v8;
int main(int argc, char* argv[]) {

	// Create a stack-allocated handle scope.
	HandleScope handle_scope;

	// Create a new context.
	Handle<Context> context = Context::New();

	// Enter the created context for compiling and
	// running the hello world script. 
	Context::Scope context_scope(context);

	// Create a string containing the JavaScript source code.
	Handle<String> source = String::New(""
		"function MyObj() "
		"{"
			"this.myArray = [1,2,2,2,2,2]; "
			"this.myDouble = Math.PI; "
		"}"

		"MyObj.prototype.myFunction = function(arg1,arg2)"
		"{"
			"return (this.myDouble + arg1 + arg2); "
		"};"

		"var globalObject = new MyObj();"
		);

	String * str = *source;
	
	// Compile the source code.
	Handle<Script> script = Script::Compile(source);

	// Run the script to get the result.
	Handle<Value> result = script->Run();

	// Convert the result to an ASCII string and print it.
	String::AsciiValue ascii(result);
	printf("%s\n", *ascii);

	// 通过变量名获取对象,全局变量隶属于Global()对象
	Local<Object> globalObject = Local<Object>::Cast(context->Global()->Get(String::New("globalObject")));

	// 获取globalObject对象的myArray属性
	Handle<Array> arrayproperty = Handle<Array>::Cast(globalObject->Get(String::New("myArray")));
	String::AsciiValue ascii2(arrayproperty);
	printf("%s\n", *ascii2);
	
	// 获取globalObject对象的myDouble属性
	Handle<Object> doubleproperty = Handle<Object>::Cast(globalObject->Get(String::New("myDouble")));
	String::AsciiValue ascii3(doubleproperty);
	printf("%s\n", *ascii3);

	// 获取globalObject对象的myFunction属性
	Local<Function> func = Local<Function>::Cast(globalObject->Get(String::New("myFunction")));
	Local<Value> argv2 [2] = {v8::Number::New(1.123123), v8::Number::New(2.234234)};
	// 调用myFunction函数对象
	String::AsciiValue ascii4(func->Call(globalObject, 2, argv2));
	printf("%s\n", *ascii4);

	// Dispose the persistent context.
	(Persistent<Context>(context)).Dispose();
	return 0;
}


运行结果:

function (arg1,arg2){return (this.myDouble + arg1 + arg2); }
1,2,2,2,2,2
3.141592653589793
6.498949653589793
请按任意键继续. . .



  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值