Created
February 11, 2016 12:13
-
-
Save xaxxon/7e0c7832fd0ae3ce79b1 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Dog { | |
void speak() = 0; | |
virtual void chew_bone() = 0; | |
}; | |
class DogImpl : public Dog { | |
int bones = 0; | |
void speak(){printf("bark\n");} | |
void chew_bone(){printf("crunch\n");} | |
}; | |
template<class CppImplClass, class BaseType> | |
struct JSBackedClass { | |
using base_type = BaseType; | |
unique_ptr<CppImplClass> cpp_impl_class; | |
v8::Global<v8::Object> js_object; | |
}; | |
// some function that wants a Dog | |
void some_function(Dog & d) {} | |
class JSDog : public JSBackedClass<Dog, DogImpl>, public Dog { | |
// js_object is a javascript object but it has a C++ Dog object hidden inside of it | |
// and any updates to the data members will update the corresponding data in the hidden C++ Dog object | |
Dog(v8::Global<v8::Object> js_object) : JS<Dog>(js_object), Animal(name) {} | |
// I think I can simplify these with macros | |
void speak() {if((result = js_object->run("speak")) != NO_METHOD_FOUND) {return result;} else {Dog d = cpp_impl_class.speak();}} | |
void chew_bone() {if((result = js_object->run("chew_bone")) != NO_METHOD_FOUND) {return result;} else {Dog d = cpp_impl_class.chew_bone();}} | |
}; | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# new Dog() calls the real C++ JSDog constructor (even though to JS it just looks like "Dog") which calls the DogImpl constructor and wraps up the returned C++ DogImpl | |
# object in a javascript object assigned to the 'dog' javascript variable | |
var dog = new Dog('fido'); | |
dog.speak = function(){println("woof")}; | |
// Takes the cpp_impl_class pointer and converts it to the base_type class which is guaranteed to be compatible and then sends it to real function | |
some_function(dog); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment