#ifndef MY_CPP_CLASS_H
#define MY_CPP_CLASS_H
#include <string>
#include "bindings/sebind/intl/common.h"
#include "bindings/sebind/sebind.h"
#include "cocos/cocos.h"
#include "core/scene-graph/Node.h"
using namespace cc;
class MyCPPClass {
public:
MyCPPClass() = default;
MyCPPClass(se::Object *jsThis) : _jsThis(jsThis) {}
// for some reason this variable is not set by constructor so I set it manually from TS
void setJsThis(se::Object *t) {
_jsThis = t;
}
// here existing Node instance is passed
void playNode(se::Object *n) {
Node* node = static_cast<Node*>(n->getPrivateData());
if (node) {
printf("ZEN77: Received Node with name: %s", node->getName().c_str());
// Here you can manipulate the node as you wish
//node->setScale(Vec3(0.5, 0.5, 0.5));
} else {
printf("ZEN77: Node is null or invalid.");
}
}
// this function is called from TS
std::string greet() {
// here JS function is called from C++
callJSFunction("onAssesmentDone");
return "ZEN77: C++ called from JS";
}
std::string callJSFunction(const std::string &name) {
if (!_jsThis) {
return "ZEN77: jsThis is not set";
}
se::Value prop;
_jsThis->getProperty(name, &prop);
if (prop.isNullOrUndefined()) {
return "ZEN77: function found!";
}
se::Value ret;
bool retVal = prop.toObject()->call({}, _jsThis, &prop);
assert(prop.isString());
return prop.toString();
}
private:
se::Object *_jsThis{nullptr};
};
#endif
test_jsb_bind ()
{
// <M> Make MyCPPClass gracefully degrade in non-native. Otherwise you get error in browser
//
MyCPPClass.prototype.onAssesmentDone = function () {
console.log("ZEN77: log: onAssesmentDone: JS called from CPP")
return "ZEN77: onAssesmentDone: JS called from CPP"
}
const myCPPInstance = new MyCPPClass();
myCPPInstance.setJsThis(myCPPInstance)
const greeting = myCPPInstance.greet();
console.log(greeting); // Outputs: "Hello from C++!"
let n = this.node
myCPPInstance.playNode(n)
}
Added declarations so TS knows the C++ class:
declare class MyCPPClass {
constructor();
// can't make the node of type Node. It gives me error. Any hint how?
playNode(node: object): void;
greet(): string;
setJsThis(t: MyCPPClass): void;
onAssesmentDone(): string;
}
That’s all the magic.
What is missing is:
make node parameter of type Node instead of object (see comment above)
provide blank implementation for MyCPPClass when being run in non-native environment.
not sure why _jsThis is not set and thus I use manual call setJsThis(…)