I'm having a similar problem as in this other post. But I'm not quite understanding how to fix this.
I have C++ objects I want to expose to the script as singletons of a particular class. I want these objects to be properties accessible to the script, but not be copyable or otherwise changed. These exposed object would have particular methods. These exposed objects would have application lifetime (they are created at the beginning and kept until the application exists).
For example, say I have this class in C++:
MyClass(const std:string& n)
const std::string& get_name() const
const std::string name;
I want to expose several instances of MyClass to Angelscript as global properties. I register the class and method doing the following:
r = engine->RegisterObjectType("MyClass", 0, asOBJ_REF|asOBJ_NOCOUNT); assert(r >= 0);
r = engine->RegisterObjectMethod("MyClass", "const string name() const", asMETHOD(MyClass, get_name), asCALL_THISCALL); assert(r >= 0);
And then I create some instances and register them as global properties:
std::shared_ptr<MyClass> foo = std::make_shared<MyClass("foo");
std::shared_ptr<MyClass> bar = std::make_shared<MyClass("bar");
r = engine->RegisterGlobalProperty("MyClass foo", foo.get()); assert(r >= 0);
r = engine->RegisterGlobalProperty("MyClass bar", bar.get()); assert(r >= 0);
Then in Angelscript, whenever I try to invoke MyClass::get_name, 'this' is the wrong value. For example, stepping through with gdb, I get the following:
foo.get() = 0x82c6f0
bar.get() = 0x82cd60
And in Angelscript, if I do:
string n = foo.name();
And setting a breakpoint in MyClass::get_name, 'this' is 0x82fd38, which is clearly something on the heap (perhaps something allocated by AS?).
I tried to follow the examples from other posts on singletons, such as this and this. But it doesn't seem to be working.
I'm using Angelscript 2.29.2.