13. embind deriving from js 类的继承和JS
#include <emscripten/bind.h> #include <string> using namespace emscripten; class Interface { public: Interface() = default; // virtual std::string invoke(const std::string &str) = 0; virtual std::string invoke(const std::string &str) { return str + " - from 'C++'"; } }; // Glue between JavaScript and C/C++; class DerivedClass : public wrapper<Interface> { public: EMSCRIPTEN_WRAPPER(DerivedClass); std::string invoke(const std::string &str) override { return call<std::string>("invoke", str); } }; EMSCRIPTEN_BINDINGS(module) { class_<Interface>("Interface") // .function("invoke", &Interface::invoke, pure_virtual()) .function("invoke", optional_override([](Interface &self, const std::string &str){ return self.Interface::invoke(str); })) // "extend" && "implement" .allow_subclass<DerivedClass>("DerivedClass"); }
__ATPOSTRUN__.push(() => { var DerivedClass = Module["Interface"].extend("Interface", { __construct: function() { this.__parent.__construct.call(this); }, __destruct: function() { this.__parent.__destruct.call(this); }, invoke: function(str) { return str + " - from 'YHSPY'"; } }); var instanceByExtend = new DerivedClass; console.log(instanceByExtend.invoke("Hello!")); // var implementations = { invoke: function(str) { return str + " - from 'YHSPY'"; } }; var instanceByImpelment = Module["Interface"].implement(implementations); console.log(instanceByImpelment.invoke("Hello!")); });
假舆马者,非利足也,而致千里;假舟楫者,非能水也,而绝江河
浙公网安备 33010602011771号