Permalink
Browse files

Added string conversion example

  • Loading branch information...
1 parent 40ec788 commit 491aa47a56a24d83462260b271a99afbbb3709ce @nikhilm committed Jan 18, 2012
Showing with 87 additions and 2 deletions.
  1. +22 −2 slides.rst
  2. +47 −0 strings/main.cc
  3. +5 −0 strings/test.js
  4. +13 −0 strings/wscript
View
@@ -144,11 +144,31 @@ Implementation:
.. code-block:: cpp
:include: simplefunctions/main.cc
- :start-after: {
- :end-before: }
+ :start-at: Handle
+ :end-at: }
explain scope.Close
+Strings to-and-fro
+------------------
+
+v8::String -> C string
+
+.. code-block:: cpp
+ :include: strings/main.cc
+ :start-after: v8;
+ :end-before: Handle<Value> Read
+
+Strings to-and-fro
+------------------
+
+C string -> v8::String
+
+.. code-block:: cpp
+ :include: strings/main.cc
+ :start-at: Handle<Value> Read
+ :end-at: }
+
Simple objects
--------------
View
@@ -0,0 +1,47 @@
+#include <stdio.h>
+#include <string.h>
+#include <v8.h>
+#include <node.h>
+using namespace v8;
+
+Handle<Value> Print(const Arguments &args) {
+ HandleScope scope;
+
+ for (int i = 0; i < args.Length(); i++) {
+ if (!args[i]->IsString())
+ continue;
+
+ // also String::AsciiValue
+ String::Utf8Value val(args[i]);
+ printf("%s ", *val); // <<<<<<
+ }
+ return Undefined();
+}
+
+Handle<Value> Read(const Arguments &args) {
+ HandleScope scope;
+
+ char str[1024];
+ fgets(str, 1023, stdin);
+
+ Local<String> v8String = String::New(str, strlen(str));
+ return scope.Close(v8String);
+}
+
+extern "C" {
+ static void Init(Handle<Object> target) {
+ HandleScope scope;
+
+ Handle<FunctionTemplate> printTpl =
+ FunctionTemplate::New(Print);
+
+ Handle<FunctionTemplate> readTpl =
+ FunctionTemplate::New(Read);
+
+ target->Set(String::New("print"),
+ printTpl->GetFunction());
+ target->Set(String::New("read"),
+ readTpl->GetFunction());
+ }
+ NODE_MODULE(strings, Init)
+}
View
@@ -0,0 +1,5 @@
+var strings = require('./build/Release/strings')
+strings.print("this", "is", 5, 6, "strings\n");
+strings.print("Enter name:");
+var name = strings.read();
+strings.print("Hi", name);
View
@@ -0,0 +1,13 @@
+import Options
+
+def set_options(opt):
+ opt.tool_options("compiler_cxx")
+
+def configure(conf):
+ conf.check_tool("compiler_cxx")
+ conf.check_tool("node_addon")
+
+def build(bld):
+ obj = bld.new_task_gen("cxx", "shlib", "node_addon")
+ obj.target = "strings"
+ obj.source = "main.cc"

0 comments on commit 491aa47

Please sign in to comment.