Hi all.

I'm new to V8 and am trying to work through the examples.  I got 
Hello_world.cc working and thought I'd expand by trying to add a javascript 
function (Print()).  I tried to follow the code in ./samples/*.cc.

I compile it with:

g++ hello_world.cc -lv8 -licuuc -licui18n -lrt   -o hello_world

The, when I run ./hello_world, I get:

<unknown>:0: Uncaught ReferenceError: print is not defined
Segmentation fault (core dumped)

I've attached the code.  Please tell me what I'm doing wrong so I can 
continue on....

Mike.

-- 
-- 
v8-users mailing list
[email protected]
http://groups.google.com/group/v8-users
--- 
You received this message because you are subscribed to the Google Groups 
"v8-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
For more options, visit https://groups.google.com/groups/opt_out.
#include <v8.h>
#include <iostream>
#include <stdio.h>

#include <assert.h>
#include <fcntl.h>
#include <string.h>
#include <stdlib.h>

using namespace v8;
using namespace std;

const char* ToCString(const v8::String::Utf8Value& value) {
  return *value ? *value : "<string conversion failed>";
}

void Print(const v8::FunctionCallbackInfo<v8::Value>& args) {
  bool first = true;
  for (int i = 0; i < args.Length(); i++) {
    v8::HandleScope handle_scope(args.GetIsolate());
    if (first) {
      first = false;
    } else {
      printf(" ");
    }
    v8::String::Utf8Value str(args[i]);
    const char* cstr = ToCString(str);
    printf("%s", cstr);
  }
  printf("\n");
  fflush(stdout);
}


int main(int argc, char* argv[]) {
  // Get the default Isolate created at startup.
  Isolate* isolate = Isolate::GetCurrent();

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

// #################################################

Handle<ObjectTemplate> global = ObjectTemplate::New(isolate);

//global->Set(v8::String::NewFromUtf8(isolate, "print"),
global->Set(String::NewFromUtf8(isolate, "print"),
              v8::FunctionTemplate::New(isolate, Print));

// #################################################

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

  // Enter the 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::NewFromUtf8(isolate, "'Hello' + ', World!';");
Handle<String> source = String::NewFromUtf8(isolate, "print('hello');");
  
  // 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 UTF8 string and print it.
  String::Utf8Value utf8(result);
  printf("%s\n", *utf8);
  return 0;
}

Reply via email to