Hello GameDevs,
I've created a custom handle class which can be used in both C++ and AngelScript to maintain correct reference count. On C++ side, it's used the same way as shared_ptr<>
, on AngelScript side it's a custom handle asOBJ_ASHANDLE
. For details see the Github repo: https://github.com/ohlidalp/RefCountingObject-AngelScript, but in a nutshell it works this way:
// Registering the reference type
Parrot::RegisterRefCountingObject(engine, "Parrot");
engine->RegisterObjectMethod("Parrot", "void Chirp()", asMETHOD(Parrot, Chirp), asCALL_THISCALL);
// Registering the factory behaviour (using 'auto handle' syntax)
engine->RegisterObjectBehaviour("Parrot", asBEHAVE_FACTORY, "Parrot@+ f()", asFUNCTION(ParrotFactory), asCALL_CDECL);
// Register handle type
ParrotPtr::RegisterRefCountingObjectPtr(engine, "ParrotPtr", "Parrot");
// Registering example interface
engine->RegisterGlobalFunction("void PutToAviary(ParrotPtr@ h)", asFUNCTION(PutToAviary), asCALL_CDECL);
engine->RegisterGlobalFunction("ParrotPtr@ FetchFromAviary()", asFUNCTION(FetchFromAviary), asCALL_CDECL);
It works perfectly but has one big usability flaw: You cannot call the object's method directly on the custom handle without an explicit cast, like FetchFromAviary().Chirp();
you'll get error “No matching symbol”. It's easily worked around by assigning, like Parrot@ parr = FetchFromAviary(); parr.Chirp();
, or by calling a conversion helper GetHandle()
like `FetchFromAviary().GetHandle().Chirp();
. However, I'm aiming for an intuitive and beginner-friendly interface for users of my project, so I wonder if there's any possibility that I missed. Of course, I can always fall back to wrappers which I'll explore as plan B, but I'm curious if there's a more intricate direct solution.
Thanks for reading