The official examples of exposing a Point class seem to assume that there will be a fixed number of instances of it in your program. It is not clear how new instances are allocated in the C++ code, when new is called in Javascript.
How would you expose a class that can have multiple instances? For example, an Image class:
var img1 = new Image( 640, 480 );
var img2 = new Image( 1024, 768 );
img1.clear( "red" );
img2.clear( "black" );
This is the best blog post I could find on exposing C++ objects to V8 Javascript . It goes into deeper detail and breaks it down into smaller steps with code snippets. Be warned: the code snippets have little inconsistencies and it took me several reads to understand. Reading my brief summary beforehand may help:
new
will be called from) to the C++ constructor. new
operator and calls the C++ class constructor. It then wraps the object by calling the wrapObject() method created in step 1.2. Now, the memory allocated in step 2.2 must be delete
'd some time. Update: The next blog entry, " Persistent Handles ," covers this in detail.
My notes on the actual code alluded to in these blog posts :
wrapPoint()
method in the blog is actually analogous to the unwrap()
method in the actual code; not wrap()
SetInternalFieldCount(0
, constructorCall
Here is a helper i wrote a while back that makes exposing and dealing with contexts in v8 pretty easy. Hope it helps.
https://gamedev.stackexchange.com/questions/2796/binding-c-and-v8-javascript-from-google/2797#2797
I don't know how to achieve this in V8 Js engine exactly, but as in the Python world, you can just do as following. your Image class:
class Image
{
public:
Image(int w, int h);
int Width(void) const;
};
write some wrapper functions and expose these functions to the Js world:
Image* Image_New(int w, int h) { return new Image(w, h); }
void Image_Delete(Image* pImage) { delete pImage; }
int Image_Width(const Image* pImage) { return pImage->Width(); }
add the following codes to your js file:
var Image = function (w, h) {
this.image = new Image(w, h);
this.Width = function() {
return Image_Width(this.image);
};
};
and now you can get you code work. Additionally, the codes above haven't take the Garbage collection mechanism into consideration, so pay some special attention to it.Sorry for my borken English!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.