I'm trying to write a function which behaves like the "console.log",
following is what I have got so far:
#include <v8.h>
#include <iostream>
#include <string>
using namespace v8;
using namespace std;
Handle<Value> print (const Arguments& args) {
HandleScope scope;
cout << args.Length() << endl;
for (int i = 0; i< args.Length(); ++i) {
cout << *String::Utf8Value (args[i]) << " ";
}
cout << endl;
return Undefined ();
}
int main(int argc, char *argv[])
{
HandleScope handle_scope;
Handle<Context> context = Context::New();
Context::Scope context_scope(context);
// Generate Function
Local<FunctionTemplate> func_tpl = FunctionTemplate::New (print);
func_tpl->SetClassName (String::NewSymbol ("print"));
Local<Function> func = func_tpl->GetFunction ();
cout << *String::Utf8Value (func) << endl;
// Generate parameters
Local<Value> args[4] = {
String::New ("I"),
String::New ("Love"),
String::New ("C++"),
String::New ("!")
};
// Call Function
func->Call (context->Global (), 4, args);
return 0;
}
The output is
function print() { [native code] }
-1074200596
Apparently the print function didn't got the arguments. Then I tried
to call the function in javascript:
// Expose function to the global
context->Global ()->Set (String::NewSymbol ("print"), func);
// Call it in js
Handle<String> source = String::New ("print ('I', 'Love', 'C++');");
Handle<Script> script = Script::Compile (source);
Handle<Value> result = script->Run ();
And I got the same result. Why is that? Did I miss something in the
code?
--
v8-users mailing list
[email protected]
http://groups.google.com/group/v8-users