Advertisement

Can I call object methods via custom handle without casting?

Started by July 01, 2024 08:32 PM
1 comment, last by WitchLord 4 months, 4 weeks ago

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

Hi Ohlidalp,

There is currently no way to dynamically dispatch a call to whatever type is held within the container class.

An explicit cast is required so AngelScript knows what method are actually available and how to call them.

- Andreas

AngelCode.com - game development and more - Reference DB - game developer references
AngelScript - free scripting library - BMFont - free bitmap font generator - Tower - free puzzle game

This topic is closed to new replies.

Advertisement