I'm attempting to wrap a C++ function that takes an object as an input so that it's accessible via Nodejs. Here's a trivial example to show what I'm trying to do.
Suppose in C++,
struct query {
string m_foo;
string m_bar;
query(string foo, string bar)
:m_foo(foo), m_bar(bar) {}
}
static string ExecuteQuery(query q); // Implemented somewhere
In Javascript (node.js) I want to be able to do,
var q = new plugin.query("foo", "bar");
var result = plugin.ExecuteQuery(q);
All of the nodejs C++ plugin examples I've found are working with simple data types and fairly trivial examples. Are there any good examples or patterns for doing something like this? With the lack of v8 documentation and cumbersome/verbose syntax of making plugins, I haven't had much luck with this on my own.
Needed,
Also, is there anything better than v8-juice/cvv8 for trying to simplify the process of wrapping C++ libraries so they're accessible via node.js?
node-canvas Within node-canvas TJ Holowaychuk has done a great job of showing object wrapping examples in C++ for passing back and use on the javascript side.
I'll extract one example below to share with you how it's done.
From Image.h
class Image: public node::ObjectWrap {
From Image.cc
Persistent<FunctionTemplate> Image::constructor;
...
Handle<Value>
Image::New(const Arguments &args) {
HandleScope scope;
Image *img = new Image;
img->data_mode = DATA_IMAGE;
img->Wrap(args.This());
return args.This();
}
Another example is the Canvas object
class Canvas: public node::ObjectWrap {
and from Canvas.cc
Handle<Value>
Canvas::New(const Arguments &args) {
HandleScope scope;
int width = 0, height = 0;
canvas_type_t type = CANVAS_TYPE_IMAGE;
if (args[0]->IsNumber()) width = args[0]->Uint32Value();
if (args[1]->IsNumber()) height = args[1]->Uint32Value();
if (args[2]->IsString()) type = !strcmp("pdf", *String::AsciiValue(args[2]))
? CANVAS_TYPE_PDF
: CANVAS_TYPE_IMAGE;
Canvas *canvas = new Canvas(width, height, type);
canvas->Wrap(args.This());
return args.This();
}
Once the node-canvas module is required it's as easy to access as any other javascript object.
fs.readFile(__dirname + '/someFile.jpg', function(err, image_data){
var Canvas = require('canvas');
var Image = Canvas.Image;
var img = new Image;
img.onload = function() {
var canvas = new Canvas(img.width,img.height);
var ctx = canvas.getContext('2d');
// grab and modify pixel data etc
}
img.src = image_data;
}
For an explanation of ObjectWrap, see nodejs addon docs.
It depends on which browser you're using, but with most of them interop between C++ and JavaScript is done via COM.